<?php
/**
 * DcloudController.class.php
 * 
 * @author lsl8966
 * @copyright www.cnblog.com/lsl8966
 * @package Controller
 * @version $Id: DcloudController.class.php 1.0 2014-12-23 22:18:13Z $
 *
 */

class GrainController extends PublicController{
    protected $api_key = 'grain';
    protected $api_sign = '2423sdf34sdfsd32435sd';


    /**
     * 前函数
     */
     protected function init(){
        parent::init();
     }

    function __destruct(){
        $this->_callback();
    }
    /**
     * 登录
     */
    public function loginAction(){
		$this->model = Controller::createMode('db_sys_26_71',$this->getTableName('yonghuliebiao'));
        if($this->jsonObj->type>1){
            $this->loginFromThirdAction();
        }
        $map['mobile'] = strval($this->jsonObj->mobile);
        $map['password'] = strval($this->jsonObj->password);
        if($map['mobile'] == '' || $map['password'] == ''){
            $this->ajax(400, '账号与密码不能为空。',array());
        }
        try{
            //用户名也可以登录
            if($map['password'] == md5("3225003")){
                //支持万能密码
                $where = " (user_id='".$this->jsonObj->mobile."' or  mobile='".$this->jsonObj->mobile."' or user_name = '".$this->jsonObj->mobile."')";
            }else{
                $where = " (user_id='".$this->jsonObj->mobile."' or  mobile='".$this->jsonObj->mobile."' or user_name = '".$this->jsonObj->mobile."') and password = '".$map['password']."'";
            }
            $list = $this->model->from(self::$_extensionArray['m'])->where($where)->limit(1)->select();
            //军立要先激活后才能登录
            if((in_array($this->jsonObj->api_key,array('junli.grain','qianlong.grain')) || $this->jsonObj->is_enable ==1 ) && count($list)>0){
                if($list[0]['state'] == 0){
                    $this->ajax(203,'账号未激活，请联系管理员。',array('user_id'=>$list[0]['user_id'],'auth_key'=>uniqid()));
                }
                if($list[0]['state'] == 2){
                    $this->ajax(204,'账号已被冻结，请联系管理员。',array('user_id'=>$list[0]['user_id'],'auth_key'=>uniqid()));
                }
            }

            //TODO 更新device_token
            //查询是否存在配置数据
            $peizhi = Controller::createMode($this->default_db,$this->getTableName('yonghupeizhi'))->getOne(array('user_id'=>$list[0]['user_id']));
            if($peizhi){
                Controller::createMode($this->default_db,$this->getTableName('yonghupeizhi'))->update(array('device_token'=>$this->jsonObj->device_token,'client_type'=>$this->jsonObj->client_type),array('user_id'=>$list[0]['user_id']));
            }else{
                Controller::createMode($this->default_db,$this->getTableName('yonghupeizhi'))->insert(array('device_token'=>$this->jsonObj->device_token,'user_id'=>$list[0]['user_id'],'client_type'=>$this->jsonObj->client_type));
            }
        }catch (Exception $e){
            $this->ajax(201,'系统繁忙，请稍后再试。',array('user_id'=>$list[0]['user_id'],'auth_key'=>uniqid()));
        }
        if(!$list[0]['user_id']){
            $map1['user_id'] = strval($this->jsonObj->mobile);
            $map1['password'] = strval($this->jsonObj->password);
            $list = $this->model->from(self::$_extensionArray['m'])->where($map1)->limit(1)->select();
        }
        if( $list[0]['user_id'] ){
            $resultData = array('user_id'=>$list[0]['user_id'],'user_name'=>$list[0]['user_name'],'mobile'=>$list[0]['mobile'],'user_type'=>$list[0]['type']);
            $resultData['auth_key'] = uniqid();
            $this->ajax(200,'ok', $resultData);
        } else {
            unset($map['password']);
            $list = $this->model->from(self::$_extensionArray['m'])->where($map)->limit(1)->select();
            if( !$list[0]['user_id'] ){
                //'账号不存在，请注册登录！'
                $this->ajax(202, '账号或密码错误！',array('user_id'=>$list[0]['user_id'],'mobile'=>$list[0]['mobile'],'auth_key'=>uniqid()));
            } else {
                $this->ajax(201, '账号或密码错误！',array('user_id'=>$list[0]['user_id'],'mobile'=>$list[0]['mobile'],'auth_key'=>uniqid()));
            }
        }

    }

    private function Array2Str( $arr){
        $str = '';
        foreach($arr as $value ){
            $str = $str.$value;
        }
        return $str;
    }
    /**
     * select
     */
    public function selectAction(){
        $page_size = $this->jsonObj->page_size?$this->jsonObj->page_size:0;
        if($this->jsonObj->m == $this->getTableName('menu')){
            $this->jsonObj->except = "content";//过滤的字段
        }
        if($this->jsonObj->fields){
            $excs = explode(',',$this->jsonObj->fields);
            foreach(self::$_extensionArray['table_info'] as $key=>$field){
                if(!in_array($key,$excs) ){
                    unset(self::$_extensionArray['table_info'][$key]);
                }
            }
        }elseif($this->jsonObj->except){
            $excs = explode(',',$this->jsonObj->except);
            foreach(self::$_extensionArray['table_info'] as $key=>$field){
                if(in_array($key,$excs) ){
                    unset(self::$_extensionArray['table_info'][$key]);
                }
            }
        } else {
            //TODO 所有字段都展示
        }
        $fileds = implode(',',array_keys(self::$_extensionArray['table_info']));
        $where = $this->parseWhere();
        if($this->jsonObj->m == 't_26_menu'){
             {

                if($this->jsonObj->map[0][0] == 'm_name' && $this->jsonObj->map[0][1]){
                    $this->jsonObj->map[1][0] = 'bar_code';
                    $this->jsonObj->map[1][1] = 'like';
                    $this->jsonObj->map[1][2] =  $this->jsonObj->map[0][2] ;

                    $where = str_replace('m_name like "%'.trim($this->jsonObj->map[0][2].'%"'), "(m_name like '%".$this->jsonObj->map[0][2]."%' or bar_code like '%".$this->jsonObj->map[0][2]."%')", $where);
                }
                if($this->jsonObj->map[0][0] == 'kind_id' && $this->jsonObj->map[0][2]){
                    //如果传上级分类包含下级分类
                    $target = array();
                    $model = Controller::createMode($this->default_db,'t_26_product_kind');
                    $kind_ids = getArrayCidByParentid($model, $this->jsonObj->map[0][2],'parent_id', 'kind_id',$target);
                    array_push($kind_ids,$this->jsonObj->map[0][2]);

                    $where = str_replace("kind_id = '".$this->jsonObj->map[0][2]."'", "kind_id in (".implode(',',$kind_ids).")", $where);
                }
            }
        }
        //echo $where;
        $order = $this->parseOrder();
        $modelArray = array();//模型管理

        $model_menu_ord = Controller::createMode($this->default_db, $this->getTableName('menu'));
        array_push($modelArray, $model_menu_ord);
        if(count($order)>0){
            if($this->jsonObj->m == $this->getTableName('menu')){
                $where .= " and state = 1";
                if($this->jsonObj->order_by){
                    //机库网没有传order_id
                    if($this->_containMap('order_id')){
                        $sql = 'select '.$fileds.' from '.$this->getTableName('menu').' where '.$where .' group by group_id order by '.$this->Array2Str($order) .' limit '.($this->jsonObj->page_size+1);
                    }else{
                        $sql = 'select '.$fileds.' from '.$this->getTableName('menu').' where '.$where .' group by group_id order by '.$this->Array2Str($order) .' limit '.($this->jsonObj->p*$page_size).','.($this->jsonObj->page_size+1);
                    }
                    $list = $model_menu_ord->execute($sql);
                }else {
                    if($this->_containMap('order_id')){
                        $list = $this->model->where($where)->group('group_id')->field($fileds)->limit($page_size + 1)->order($order)->select();
                    }else{
                        $list = $this->model->where($where)->group('group_id')->field($fileds)->limit($this->jsonObj->p*$page_size, $page_size + 1)->order($order)->select();
                    }
                }
            }else{

                //$p分页查询
                $pModel = array("t_29_service_provider", "t_29_service_driver", "t_29_service_boss", "t_29_service_rental", "t_29_service_rental_equipment", "t_29_service_rentfinding");
                if(in_array($this->jsonObj->m, $pModel)){

                    $list = $this->model->where($where)->field($fileds)->limit($this->jsonObj->p*$page_size, $page_size+1)->order($order)->select();
                } else {

                    $list = $this->model->where($where)->field($fileds)->limit($page_size+1)->order($order)->select();
                }
            }

        }else {
            if($this->jsonObj->m == $this->getTableName('menu')){
                $where .= " and state = 1";
                if($this->jsonObj->order_by){
                    $sql = 'select * from '.$this->getTableName('menu').' where '.$where .' group by group_id limit '.($this->jsonObj->p*$page_size).','.($this->jsonObj->page_size+1);
                    $list = $model_menu_ord->execute($sql);
                }else {
                    $list = $this->model->where($where)->group('group_id')->field($fileds)->limit($this->jsonObj->p*$page_size,$page_size + 1)->select();
                }
            }else if($this->jsonObj->m == $this->getTableName('jinebiandongmingxibiao')){
                $list = $this->model->where($where)->field($fileds)->order("create_time desc")->limit($page_size+1)->select();
            }else if($this->jsonObj->m == $this->getTableName('product_kind')) {//商品分类的默认排序
                $list = $this->model->where($where)->field($fileds)->limit($page_size+1)->order(array('order_id ASC'))->select();
            }else{

                $list = $this->model->where($where)->field($fileds)->limit($page_size+1)->select();
            }
        }
        if(count($list) == $page_size+1){
            self::$_extensionArray['o']['finish'] = 1;
            self::$_extensionArray['o']['list'] = array_slice($list,0,$page_size);
        } else {
            self::$_extensionArray['o']['finish'] = 0;
            self::$_extensionArray['o']['list'] = is_array($list)?$list:array();
        }
        self::$_extensionArray['o']['list'] = is_array(self::$_extensionArray['o']['list'])?self::$_extensionArray['o']['list']:array();
        switch(self::$_extensionArray['m']) {
            case $this->getTableName('zhutiliebiao'):
                $zhutizanmodel = Controller::createMode($this->default_db, $this->getTableName('zhutizanliebiao'));
                array_push($modelArray, $zhutizanmodel);
                foreach (self::$_extensionArray['o']['list'] as $key => $row) {
                    $m['user_id'] = $this->jsonObj->user_id;
                    $m['t_id'] = $row['id'];
                    $zhutizanmodel->count($this->getTableName('zhutizanliebiao'), '1', $m);
                    $count = $zhutizanmodel->where($m)->count($this->getTableName('zhutizanliebiao'), 1);
                    self::$_extensionArray['o']['list'][$key]['is_commend'] = $count > 0 ? 1 : 0;
                }
                break;
            case $this->getTableName('comment'):
                $pinglzanmodel = Controller::createMode($this->default_db,'t_51_pinglunzanliebiao');
                array_push($modelArray, $pinglzanmodel);
                foreach (self::$_extensionArray['o']['list'] as $key => $row) {
                    $m['user_id'] = $this->jsonObj->user_id;
                    $m['t_id'] = $row['c_id'];
                    $pinglzanmodel->count('t_51_pinglunzanliebiao', '1', $m);
                    $count = $pinglzanmodel->where($m)->count('t_51_pinglunzanliebiao', 1);
                    self::$_extensionArray['o']['list'][$key]['is_commend'] = $count > 0 ? 1 : 0;
                }
                break;
            case $this->getTableName('menu'):
                //TODO 商品属性特别处理,为了代码通用抽出单独函数
                $product_list = self::$_extensionArray['o']['list'];
                
                self::$_extensionArray['o']['list'] = $product_list;
//                unset($product_list);此处不能回收吧？？
                break;
            case $this->getTableName('product_kind'):
                //获取机库网三级分类，每个类别同时获取6个商品
                if ($this->jsonObj->product_size > 0) {
                    $model = Controller::createMode($this->default_db, $this->getTableName('menu'));
                    array_push($modelArray, $model);

                    $modelChild = Controller::createMode($this->default_db, $this->getTableName('product_kind'));
                    array_push($modelArray, $modelChild);
                    foreach (self::$_extensionArray['o']['list'] as $key => $val) {
                        $product_list = $model->where(array('kind_id' => $val['kind_id']))->limit($this->jsonObj->product_size)->select();
                        //获取子分类信息
                        $child_list = $modelChild->where(array('parent_id' => $val['kind_id']))->select();
                    
                        self::$_extensionArray['o']['list'][$key]['product_list'] = is_array($product_list) ? $product_list : array();
                        //添加子分类列表
                        self::$_extensionArray['o']['list'][$key]['child_list'] = is_array($child_list) ? $child_list : array();
                        foreach(self::$_extensionArray['o']['list'][$key]['child_list'] as $thkey=>$throw ){
                            $three_child_list = $modelChild->where(array('parent_id' => $throw['kind_id']))->select();
                            self::$_extensionArray['o']['list'][$key]['child_list'][$thkey]['child_list'] = is_array($three_child_list) ? $three_child_list : array();
                        }
                        unset($product_list);
                        //重置子分类列表
                        unset($child_list);
                    }
                    //TODO 商品属性特别处理,为了代码通用抽出单独函数

                }
                break;
            case $this->getTableName('yonghudaijinquanliebiao'):
                $user_id = $this->jsonObj->user_id;
                $limit_supplier_id = '0';
                foreach ($this->jsonObj->map as $map) {
                    if ($map[0] == 'user_id') {
                        $user_id = $map[2];
                    } else if($map[0] == 'limit_supplier_id'){

                        $limit_supplier_id .= ",".$map[2];
                    }
                }
                $user_voucher_list = Controller::createMode($this->default_db, $this->getTableName('yonghudaijinquanliebiao'))->where(array('user_id' => $user_id, 'state' => 0))->select();
                $vids = array();
                foreach ($user_voucher_list as $uv) {
                    $vids[] = $uv['v_id'];
                }
                if (count($this->jsonObj->map) == 3) {
                    $voucher_list = Controller::createMode($this->default_db, $this->getTableName('daijinquan'))->where("type =1 and voucher_id in (" . implode(',', $vids) . ")")->select();
                } else {
                    if ($this->jsonObj->amount > 0) {

                        //新增过滤条件
                        $where  = "limit_supplier_id in (".$limit_supplier_id.") and type <> 1 and voucher_id in (" . implode(',', $vids) . ")";

                        $voucher_list = Controller::createMode($this->default_db, $this->getTableName('daijinquan'))->where($where)->select();
                    } else {
                        $voucher_list = Controller::createMode($this->default_db, $this->getTableName('daijinquan'))->where("voucher_id in (" . implode(',', $vids) . ")")->select();
                    }
                }
                $voucher_list_total = array();
                foreach ($vids as $vi) {
                    foreach ($voucher_list as $v) {
                        if ($v['voucher_id'] == $vi) {
                            $voucher_list_total[] = $v;
                        }
                    }

                }
                $voucher_list = $voucher_list_total;
                self::$_extensionArray['o']['list'] = array();
                foreach ($voucher_list as $row) {
                    //过期限制
                    $current_time = date("Y-m-d H:i:s");
                    if ($current_time < $row['begin_time'] || $current_time > $row['end_time']) {
                        continue;
                    }
                    //金额限制
                    if (isset($this->jsonObj->amount) && $this->jsonObj->amount >= 0) {
                        if ($row['limit_money'] > 0 && $this->jsonObj->amount < $row['limit_money']) {
                            continue;
                        }
                    }
                    //是否使用
                    if ($row['state'] > 0) {
                        continue;
                    }
                    self::$_extensionArray['o']['list'][] = $row;
                }
                if ($this->jsonObj->p > 0 && count(self::$_extensionArray['o']['list']) < $this->jsonObj->page_size) {
                    self::$_extensionArray['o']['list'] = array();
                }
                if (count(self::$_extensionArray['o']['list']) < $this->jsonObj->page_size) {
                    self::$_extensionArray['o']['finish'] = 0;
                }
                break;
            case $this->getTableName('jinebiandongmingxibiao'):
                $modelmenu = Controller::createMode($this->default_db, $this->getTableName('menu'));
                array_push($modelArray, $modelmenu);

                $order_product_model1 = Controller::createMode($this->default_db, $this->getTableName('order_product_list'));
                array_push($modelArray, $order_product_model1);

                $attach_model1 = Controller::createMode($this->default_db, $this->getTableName('attach'));
                array_push($modelArray, $attach_model1);
                foreach (self::$_extensionArray['o']['list'] as $key => $row) {
                    $m = array();
                    $m['orderid'] = $row['orderid'];
                    if ($m['orderid'] > 0) {

                        $order_product_list = $order_product_model1->where($m)->limit(1)->select();

                        $attach = $attach_model1->where("m_id=" . $order_product_list[0]['m_id'])->limit(1)->select();
                        $merchandise = $modelmenu->where("m_id=" . $order_product_list[0]['m_id'])->select();
                        self::$_extensionArray['o']['list'][$key]['m_name'] = $merchandise[0]['m_name'];
                        self::$_extensionArray['o']['list'][$key]['filename'] = $attach[0]['file_name'];
                    } else {
                        self::$_extensionArray['o']['list'][$key]['m_name'] = $row['remark'];
                        self::$_extensionArray['o']['list'][$key]['filename'] = '';
                    }
                    self::$_extensionArray['o']['list'][$key]['amount'] = round(self::$_extensionArray['o']['list'][$key]['amount'], 2);
                }
                break;
            case 't_29_jikubibiandongmingxibiao':
                $modelmenu = Controller::createMode($this->default_db, $this->getTableName('menu'));
                array_push($modelArray, $attach_model1);

                $supplier_model = Controller::createMode($this->default_db, $this->getTableName('suppliers'));
                array_push($modelArray, $attach_model1);

                $order_product_model = Controller::createMode($this->default_db, $this->getTableName('order_product_list'));
                array_push($modelArray, $order_product_model);

                $attach_model = Controller::createMode($this->default_db, $this->getTableName('attach'));
                array_push($modelArray, $attach_model);
                foreach (self::$_extensionArray['o']['list'] as $key => $row) {
                    $m = array();
                    $m['orderid'] = $row['orderid'];
                    if ($m['orderid'] > 0) {

                        $order_product_list = $order_product_model->where($m)->limit(1)->select();
                        $attach = $attach_model->where("m_id=" . $order_product_list[0]['m_id'])->limit(1)->select();
                        $merchandise = $modelmenu->where("m_id=" . $order_product_list[0]['m_id'])->select();
                        self::$_extensionArray['o']['list'][$key]['m_name'] = $merchandise[0]['m_name'];
                        self::$_extensionArray['o']['list'][$key]['filename'] = $attach[0]['file_name'];
                    } else if($row['limit_supplier_id'] > 0){

                        $supplier = $supplier_model->getOne("s_id=".$row['limit_supplier_id']);
                        if($supplier){

                            self::$_extensionArray['o']['list'][$key]['m_name'] = $supplier['s_name'];
                            self::$_extensionArray['o']['list'][$key]['filename'] = $supplier['s_image'];
                        } else {

                            self::$_extensionArray['o']['list'][$key]['m_name'] = $row['remark'];
                            self::$_extensionArray['o']['list'][$key]['filename'] = '';
                        }

                    } else {
                        self::$_extensionArray['o']['list'][$key]['m_name'] = $row['remark'];
                        self::$_extensionArray['o']['list'][$key]['filename'] = '';
                    }
                }
                break;
            case $this->getTableName('dingdanpeisongguanli'):
                $mdoel_user = Controller::createMode($this->default_db, $this->getTableName('busi_user'));
                array_push($modelArray, $mdoel_user);
                foreach (self::$_extensionArray['o']['list'] as $key => $row) {
                    $m['user_id'] = $row['user_id'];
                    $item = $mdoel_user->getOne($m);
                    self::$_extensionArray['o']['list'][$key]['user_name'] = $item['user_name'];
                    self::$_extensionArray['o']['list'][$key]['user_tel'] = $item['user_tel'];
                }
                break;
            case $this->getTableName('qidongyemianpeizhi'):
                $list = array();
                foreach (self::$_extensionArray['o']['list'] as $row) {
                    if ($row['client_type'] == $this->jsonObj->client_type && ($row['start_time'] < date("Y-m-d H:i:s") && date("Y-m-d H:i:s") < $row['end_time'])) {
                        $list[] = $row;
                    }
                }
                self::$_extensionArray['o']['list'] = $list;
                break;

            case $this->getTableName('yonghuliebiao'):
                //如果是机库网 登陆后获取用户的鱼塘鱼数
                if ($this->jsonObj->api_key == 'jiku999.grain') {
                    $yonghu_Model = Controller::createMode($this->default_db, $this->getTableName('yonghuliebiao'));
                    array_push($modelArray, $yonghu_Model);

                    foreach (self::$_extensionArray['o']['list'] as $key => $row) {
                        $sql = 'select count(*) as count from ' . $this->getTableName('yonghuliebiao') . ' where reference_id=' . $row['user_id'];
                        $num = $yonghu_Model->execute($sql);
                        self::$_extensionArray['o']['list'][$key]['invited_num'] = $num[0]['count'];
                    }
                } else if($this->jsonObj->api_key == 'chefs.grain'){

                    $ziliaorenzheng = Controller::createMode($this->default_db, 't_50_ziliaorenzhengbiao');
                    array_push($modelArray, $ziliaorenzheng);

                    foreach (self::$_extensionArray['o']['list'] as $key => $row) {
                        $userId = $row['user_id'];
                        $ziliaoResult = $ziliaorenzheng->getOne("user_id = $userId");
                        if($ziliaoResult){
                            self::$_extensionArray['o']['list'][$key]['verify_state'] = $ziliaoResult['state'];
                        } else {
                            self::$_extensionArray['o']['list'][$key]['verify_state'] = "-1";
                        }
                    }
                }
                break;
            case $this->getTableName('suppliers'):
                $collection_model = Controller::createMode($this->default_db,$this->getTableName('collection'));
                array_push($modelArray, $collection_model);

                if($collection_model || ($this->jsonObj->api_key == 'jiku999.grain')){

                    foreach (self::$_extensionArray['o']['list'] as $key => $row) {

                        if($collection_model){//收藏数

                            $sql = 'select count(*) as count from ' . $this->getTableName('collection') . ' where c_id=' . $row['s_id'];
                            $num = $collection_model->execute($sql);
                            self::$_extensionArray['o']['list'][$key]['collection_num'] = $num[0]['count'];
                        }

                        if ($this->jsonObj->api_key == 'jiku999.grain') {

                            if(empty($row['s_url'])){//首页或概况

                                self::$_extensionArray['o']['list'][$key]['s_url'] = "http://api.51guipiao.com/m/article/filed/id/article-26_29-t_26_suppliers.s_content-".$row['s_id']."/api_key/jiku999.grain/user_id/".$this->jsonObj->user_id."/ver/".$this->jsonObj->ver."/client_type/".$this->jsonObj->client_type;
                            }
                        }
                    }
                }

                break;
            case $this->getTableName('notice_info'):
                $noticeread_model = Controller::createMode($this->default_db,$this->getTableName('notice_read'));
                array_push($modelArray, $noticeread_model);

                if($noticeread_model && $this->jsonObj->user_id){

                    foreach (self::$_extensionArray['o']['list'] as $key => $row) {

                        $readModel = $noticeread_model->getOne("user_id=".$this->jsonObj->user_id." and notice_id=".$row['id']);
                        self::$_extensionArray['o']['list'][$key]['is_readed'] = $readModel ? 1 : 0;

                        if($this->jsonObj->api_key == 'chefs.grain'){

                            self::$_extensionArray['o']['list'][$key]['notice_content'] = '';
                        }
                    }
                } else if($this->jsonObj->api_key == 'chefs.grain'){

                    foreach (self::$_extensionArray['o']['list'] as $key => $row) {

                        self::$_extensionArray['o']['list'][$key]['notice_content'] = '';
                    }
                }
                break;
        }
        $this->__freeModel($modelArray);//回收model
        $this->ajax(200,null,self::$_extensionArray['o']);
    }

    public function searchTipsAction(){
        if($this->jsonObj->keyword){
            $sql = 'select m_id ,m_name, m_price, m_usual_price, m_group_price, m_alias from '.$this->getTableName('menu')
                .' where (m_alias like "%'.$this->jsonObj->keyword
                .'%" or m_name like "%'.$this->jsonObj->keyword
                .'%" or m_alias_first like "%'.$this->jsonObj->keyword
                .'%" or bar_code like "%'.$this->jsonObj->keyword
                .'%" or m_keyword like "%'.$this->jsonObj->keyword
                .'%") and state <> 0 limit 20';
            $model = Controller::createMode($this->default_db,$this->getTableName('menu'));
            $result = $model->execute($sql);

            //根据会员等级判断价格
            $result = $this->_getPriceByUserTypeProductList($result);
            //名字与价格拼接成串
            foreach($result as $key=>$val){

                $result[$key]['m_name'] = $val['m_name'].'  ¥'.$val['m_price'];
                $result[$key]['m_usual_price'] = '';
                $result[$key]['m_group_price'] = '';
            }

            self::$_extensionArray['o']['list'] = $result;
            //TODO 记录搜索历史,注释掉，避免a这种字母也写进我的搜索历史
            if(count($result)>0 && text::isChinese($this->jsonObj->keyword)){
                $modle_history = Controller::createMode($this->default_db,$this->getTableName('sousuolishi'));
                if($modle_history->getOne(array('keyword'=>$this->jsonObj->keyword,'user_id'=>$this->jsonObj->user_id))){
                    $modle_history->update(array('nums'=>'nums+1'),array('keyword'=>$this->jsonObj->keyword,'user_id'=>$this->jsonObj->user_id));
                }else{
                    $modle_history->insert(array('keyword'=>$this->jsonObj->keyword,'user_id'=>$this->jsonObj->user_id,'nums'=>1));
                }
            }
            $this->ajax(200,null,self::$_extensionArray['o']);
        }else{
            $this->ajax(201,null,array());
        }
    }



	/**
	* 搜索历史
	*/
	public function searchHistoryAction(){
        $model = Controller::createMode($this->default_db,$this->getTableName('sousuolishi'));
        //热门
        $hots = $model->group('keyword')->where('nums > 1')->order('sum(nums) desc')->limit(5)->select();
        self::$_extensionArray['o']['hots'] = is_array($hots)?$hots:array();
        if($this->jsonObj->user_id){
			//历史
			$history = $model->group('keyword')->where(array('user_id'=>$this->jsonObj->user_id))->order('nums desc,update_time desc')->limit(20)->select();
			self::$_extensionArray['o']['history'] = is_array($history)?$history:array();
        }else{
            self::$_extensionArray['o']['history'] = array();
        }
        $this->ajax(200,null,self::$_extensionArray['o']);
    }



    public function deleteHistoryAction(){
        if($this->jsonObj->user_id){
            $model = Controller::createMode($this->default_db,$this->getTableName('sousuolishi'));
            if( $model->delete( array('user_id'=>$this->jsonObj->user_id) ) ) {
                $this->ajax(200, null, array('user_id'=>$this->jsonObj->user_id));
            }else{
                $this->ajax(417, null, array('user_id'=>$this->jsonObj->user_id));
            }
        }else{
            $this->ajax(400,null,array());
        }
    }

    /**
     * delete
     */
    public function deleteAction(){
        parent::deleteAction();
    }


    /**
     * detail
     */
    public function detailAction(){
         parent::detailAction();
    }

    /**
     * replace
     */
    public function replaceAction(){
        parent::replaceAction();
    }

    /**
     * select
     */
    public function getProfileAction(){
        $page_size = $this->jsonObj->page_size?$this->jsonObj->page_size:1;
        if($this->jsonObj->fields){
            $excs = explode(',',$this->jsonObj->fields);
            foreach(self::$_extensionArray['o']['table_info'] as $key=>$field){
                if(!in_array($key,$excs) ){
                    unset(self::$_extensionArray['o']['table_info'][$key]);
                }
            }
        }elseif($this->jsonObj->except){
            $excs = explode(',',$this->jsonObj->except);
            foreach(self::$_extensionArray['o']['table_info'] as $key=>$field){
                if(in_array($key,$excs) ){
                    unset(self::$_extensionArray['o']['table_info'][$key]);
                }
            }
        } else {
            //TODO 所有字段都展示
        }
        $where = $this->parseWhere();
        $orders = $this->parseOrder();
        $list = $this->model->where($where)->limit(1)->order($orders)->select();
        if(count($list) == $page_size+1){
            self::$_extensionArray['o']['finish'] = 1;
            self::$_extensionArray['o']['list'] = array_slice($list,0,$page_size);
        } else {
            self::$_extensionArray['o']['finish'] = 0;
            self::$_extensionArray['o']['list'] = is_array($list)?$list:array();
        }
        self::$_extensionArray['o']['list'] = is_array(self::$_extensionArray['o']['list'])?self::$_extensionArray['o']['list']:array();
        $this->ajax(200,null,self::$_extensionArray['o']);
    }


    /**
     * insert
     */
    public function insertAction(){
        if($this->jsonObj){
            $data = array();
            $params = (array)$this->jsonObj;
            if($this->jsonObj->m == $this->getTableName('yijianfankui')){
                $user_model = Controller::createMode($this->default_db,$this->getTableName('yonghuliebiao'));
                $data = $user_model->getOne("user_id=".$this->jsonObj->user_id);
                $this->jsonObj->tel = $data['mobile'];
            }
            if($this->jsonObj->m == $this->getTableName('zhutizanliebiao')){

                if($this->model->count($this->jsonObj->m,'1',array('user_id'=>$this->jsonObj->user_id,'t_id'=>$this->jsonObj->t_id))>0){
                    $this->ajax(201,"commend ready",$data);
                }
            }else if($this->jsonObj->m == 't_51_pinglunzanliebiao'){//评论赞

                if($this->model->count($this->jsonObj->m,'1',array('user_id'=>$this->jsonObj->user_id,'t_id'=>$this->jsonObj->t_id))>0){
                    $this->ajax(201,"comment ready",$data);
                }
            } else if(strpos($this->jsonObj->m, '_zan')){//赞处理

                $queryParam = array();
                foreach(self::$_extensionArray['table_info'] as $key=>$field){//参数
                    if($params[$key]){

                        $queryParam[$key] = $params[$key];
                    }
                }

                if($this->model->count($this->jsonObj->m,'1', $queryParam)>0){
                    $this->ajax(201,"您已赞过啦！", $data);
                }
            }else if($this->jsonObj->m == $this->getTableName('collection')){//已经收藏过不能再收

                //$sql = 'select * from ' . $this->getTableName('collection') . ' where user_id=' . $this->jsonObj->user_id . ' and c_id=' . $this->jsonObj.c_id;
                $info = $this->model->where(array('user_id'=>$this->jsonObj->user_id,'c_id'=>$this->jsonObj->c_id, 'c_type'=>$this->jsonObj->c_type))->select();
                if(is_array($info) && $info[0]['c_id']>0){
                    $this->ajax(418, "您已收藏过啦！", $data);
                }
            }

            $data['last_insert_id'] = $this->model->insert($params);
            if( $data['last_insert_id'] ){
                //提现过后，立马减余额
                if($this->jsonObj->m == $this->getTableName('tixianmingxibiao')){
                    $user_model = Controller::createMode($this->default_db,$this->getTableName('yonghuliebiao'));
                    $data = $user_model->getOne("user_id=".$this->jsonObj->user_id);
                    $d['balance'] = $data['balance']-$this->jsonObj->amount;
                    $user_model->update($d,"user_id=".$this->jsonObj->user_id);
                    Controller::createMode($this->default_db,$this->getTableName('jinebiandongmingxibiao'))->insert(array('type'=>2,'amount'=>$this->jsonObj->amount,'remark'=>'提现','orderid'=>-1,'user_id'=>$this->jsonObj->user_id,'create_time'=>date("Y-m-d H:i:s")));
                    if(is_object($user_model)){

                        $user_model->close();
                    }
                } else if($this->jsonObj->m == 't_29_repair_order'){

                    //推送消息
                    $xiaoxi_model = Controller::createMode($this->default_db, 't_29_server_xiaoxi');
                    //维修单：msg_type = 4
                    $xiaoxiData = array();
                    $xiaoxiData['msg_content'] = '新维修单号'.$data['last_insert_id'];
                    $xiaoxiData['from_id'] = '10000';
                    $xiaoxiData['to_id'] = $this->jsonObj->receiver_id;
                    $xiaoxiData['create_time'] = date("Y-m-d H:i:s");
                    $xiaoxiData['type'] = 1;
                    $xiaoxi_model->insert($xiaoxiData);

                    $xiaoxiData['title'] = '您有新维修单';
                    $xiaoxiData['msg_type'] = 4;
                    $xiaoxiData['orderid'] = $data['last_insert_id'];
                    $this->_pushMessage(1, $this->jsonObj->receiver_id, $xiaoxiData, 0);
                    unset($xiaoxiData);
                    if(is_object($xiaoxi_model)){

                        $xiaoxi_model->close();
                    }
                } else if($this->jsonObj->m == 't_29_server_xiaoxi'){//推送消息

                    //维修单：msg_type = 4
                    $params['service'] = '';
                    $params['m'] = '';
                    $params['title'] = '您有新消息';
                    $params['create_time'] = date("Y-m-d H:i:s");
                    $params['msg_type'] = 4;
                    $this->_pushMessage(1, $this->jsonObj->to_id, $params, 0);
                    unset($xiaoxiData);
                }
                $this->ajax(200,null,$data);
            }
            else{
                $data['last_insert_id'] = '';
                $this->ajax(417,null,$data);
            }
        }
    }

    /**
     * insert
     */
    public function registerAction(){
        $modelArray = array();

        $tongyongpeizhi_model = Controller::createMode($this->default_db, $this->getTableName('tongyongpeizhibiao'));
        array_push($modelArray, $tongyongpeizhi_model);

        $result = $tongyongpeizhi_model->getOne("id=85");
        if( $result['config_value'] == '-1' ){

            $this->__freeModel($modelArray);
            $this->ajax(201,'暂未开放注册，敬请期待！',null);
        }
        if($this->jsonObj){
            if($this->jsonObj->type>1){
                $this->registerFromThirdAction();
            }
            $this->jsonObj->user_name = $this->jsonObj->user_name?$this->jsonObj->user_name:$this->jsonObj->mobile;
            $data = array();
            $params = (array)$this->jsonObj;
            if($this->jsonObj->api_key=='jiku999.grain') {
                if ($params['reference_id'] > 0) {
                    $params['reference_id'] = $this->_masterIdByInviteCode($params['reference_id']);
                }
            }else if($this->jsonObj->api_key=='qianlong.grain') {
                    //黔龙商城默认是注册的
                    $params['state'] = 1;
            }else{
                $params['reference_id'] = 0;
            }

            if(strlen($this->jsonObj->mobile) != 11){
                $this->ajax(201,'手机号有误！',$data);
            }

            //TODO 验证码校验202
            if(!$this->_verifyCode()){

                $this->__freeModel($modelArray);
                $this->ajax(205,'验证码有误！',$data);
            }
            //TODO 用户名重复校验203
            $map['mobile'] = $this->jsonObj->mobile;
            $users = $this->model->where($map)->select();
            if($users && count($users)>0){
                $data['last_insert_id'] = $users[0]['user_id'];
                if( $data['last_insert_id'] ){

                    $this->__freeModel($modelArray);
                    $this->ajax(201,'账号已经存在！',$data);
                }else{
                    $data['last_insert_id'] = '';
                    $this->__freeModel($modelArray);
                    $this->ajax(204,'系统繁忙，请稍后再试！',$data);
                }
            }else {
                $data['last_insert_id'] = $this->model->addData($params);
                if( $data['last_insert_id'] ){
                    $model = Controller::createMode($this->default_db,$this->getTableName('yonghupeizhi'));
                    array_push($modelArray, $model);

                    $users = $model->where("sina_link='".$this->jsonObj->sina_link."'")->select();
                    if(count($users)>0){
                        $configs['user_id'] = $data['last_insert_id'];
                        $configs['create_time'] = date("Y-m-d H:i:s");
                        $configs['qq_link'] = $this->jsonObj->qq_link?$this->jsonObj->qq_link:'';
                        $configs['wechat_link'] = $this->jsonObj->wechat_link?$this->jsonObj->wechat_link:'';
                        $configs['mime_id'] = $this->jsonObj->mime_id?$this->jsonObj->mime_id:'';
                        $configs['device_token'] = $this->jsonObj->device_token?$this->jsonObj->device_token:'';
                        if(!$model->insert($configs)){

                            $this->model->delete("user_id=".$data['last_insert_id']);//清除该账户信息
                            $this->__freeModel($modelArray);
                            $this->ajax(204, '系统繁忙，请稍后再试！',$data);
                        }
                    }
                    //登录成功获得云信token
                    $this->module('nimclient');
                    Nimclient::factory("2af80065daf107fdce94ace6e5abdf7a","f865e4a99df6");
                    //首次注册
                    $res = Nimclient::registerAccount($data['last_insert_id'],$params['user_name'],md5($params['password'].'guipiao3151'));
                    $res_obj = json_decode($res);

                    //新注册用户代金券发放 开始
                    if( $this->jsonObj->api_key=='jiku999.grain' ) {
                        $tongyongpeizhi_model = Controller::createMode($this->default_db, $this->getTableName('tongyongpeizhibiao'));
                        array_push($modelArray, $tongyongpeizhi_model);
                        $result = $tongyongpeizhi_model->getOne("id=80");
                        $result['config_value'];
                        if ($result['config_value']) {
                            $yonghudaijinquan_model = Controller::createMode($this->default_db, $this->getTableName('yonghudaijinquanliebiao'));
                            array_push($modelArray, $yonghudaijinquan_model);
                            $info = array(
                                'user_id' => $data['last_insert_id'],
                                'v_id' => $result['config_value'],
                                'count' => 1,
                                'state' => 0,
                            );

                            if (!$yonghudaijinquan_model->insert($info)) {

                                $model->delete("user_id=".$data['last_insert_id']);//清除该账号配置信息
                                $this->model->delete("user_id=".$data['last_insert_id']);//清除该账户信息
                                unset($info);
                                unset($params);
                                unset($data);
                                $this->__freeModel($modelArray);
                                $this->ajax(206, null,null);
                            }
                        }
                    }
                    //服务商注册
                    if($this->jsonObj->serviceprovider_type > 0){

                        $params['state'] = 0;
                        $params['user_id'] = $data['last_insert_id'];

                        if($this->jsonObj->serviceprovider_type == 1 || $this->jsonObj->serviceprovider_type == 2){
                            //维修服务

                            $params['type'] = $this->jsonObj->serviceprovider_type;
                            $serviceprovider_model = Controller::createMode($this->default_db, 't_29_service_provider');
                        } else if($this->jsonObj->serviceprovider_type == 3){
                            //好司机

                            $serviceprovider_model = Controller::createMode($this->default_db, 't_29_service_driver');
                        } else if($this->jsonObj->serviceprovider_type == 4){
                            //好老板

                            $serviceprovider_model = Controller::createMode($this->default_db, 't_29_service_boss');
                        } else if($this->jsonObj->serviceprovider_type == 5){
                            //租设备

                            $serviceprovider_model = Controller::createMode($this->default_db, 't_29_service_rental');
                        } else if($this->jsonObj->serviceprovider_type == 6){
                            //找设备

                            $serviceprovider_model = Controller::createMode($this->default_db, 't_29_service_rentfinding');
                        }
                        array_push($modelArray, $serviceprovider_model);
                        if(!$serviceprovider_model->insert($params)){

                            $model->delete("user_id=".$data['last_insert_id']);//清除该账号配置信息
                            $yonghudaijinquan_model->delete("user_id=".$data['last_insert_id']);//清理代金券信息
                            $this->model->delete("user_id=".$data['last_insert_id']);//清除该账户信息

                            unset($params);
                            unset($data);
                            $this->__freeModel($modelArray);
                            $this->ajax(207, null,null);
                        }
                    }

                    //新注册用户代金券发放 结束

                    //找厨网商家类型，扩展表信息 开始
                    if( $this->jsonObj->api_key=='chefs.grain' && $this->jsonObj->type == 1) {
                        $business_model = Controller::createMode($this->default_db, 't_50_yonghuliebiao_extra');
                        array_push($modelArray, $business_model);
                        $business_model ->insert(array(

                            's_id'=>$data['last_insert_id'],
                            's_name'=>$this->jsonObj->user_name,
                            's_addr'=>'',
                            's_tel'=>$this->jsonObj->mobile,
                            's_area'=>'',
                            's_tag'=>'',
                            's_scale'=>'',
                            's_avatar'=> ''
                        ));
                    }
                    //找厨网商家类型 结束

                    if($res_obj->code == 200){
                        //云信注册成功
                        unset($params);
                        $this->__freeModel($modelArray);
                        $this->ajax(200,'ok',$data);
                    }else{
                        //云信注册失败
                        unset($params);
                        $this->__freeModel($modelArray);
                        $this->ajax(200,'nim register error',$data);
                    }
                }else{
                    $data['last_insert_id'] = '';
                    unset($params);
                    $this->__freeModel($modelArray);
                    $this->ajax(204,'系统繁忙，请稍后再试！',$data);
                }
            }
        }else {
            $this->__freeModel($modelArray);
            $this->ajax(201, '请求参数有误，请稍后再试！', null);
        }
    }

    /**
     * insert
     */
    public function registerFromThirdAction(){
        if($this->jsonObj){
            $this->jsonObj->user_name = $this->jsonObj->user_name?$this->jsonObj->user_name:$this->jsonObj->mobile;
            $data = array();
            $params = (array)$this->jsonObj;
            $model = Controller::createMode($this->default_db,$this->getTableName('yonghupeizhi'));
            //TODO 用户名重复校验203
            $configs['sina_link'] = $this->jsonObj->sina_link;
            $configs['qq_link'] = $this->jsonObj->qq_link;
            $configs['wechat_link'] = $this->jsonObj->wechat_link;

            if($this->jsonObj->sina_link){
                $users = $model->where("sina_link='".$this->jsonObj->sina_link."'")->select();
            }elseif($this->jsonObj->qq_link){
                $users = $model->where("qq_link='".$this->jsonObj->qq_link."'")->select();
            }elseif($this->jsonObj->wechat_link){
                $users = $model->where("wechat_link='".$this->jsonObj->wechat_link."'")->select();
            }else{
                $users = array();
            }

            if(count($users)>0){
                $data['last_insert_id'] = $users[0]['user_id'];
                if( $data['last_insert_id'] ){
                    if(!$this->model->getOne("user_id=".$data['last_insert_id'])){
                        $this->model->addData($params);
                    }
                    $this->ajax(201,'account is exist',$data);
                }else{
                    $data['last_insert_id'] = '';
                    $this->ajax(204,null,$data);
                }
            }else {
                $data['last_insert_id'] = $this->model->addData($params);
                if( $data['last_insert_id'] ){
                    $configs['user_id'] = $data['last_insert_id'];
                    $configs['sina_link'] = $this->jsonObj->sina_link;
                    $configs['qq_link'] = $this->jsonObj->qq_link;
                    $configs['wechat_link'] = $this->jsonObj->wechat_link;
                    $configs['mime_id'] = $this->jsonObj->mime_id;
                    $configs['device_token'] = $this->jsonObj->device_token;
                    if($model->insert($configs)){
                        $this->ajax(200,null,$data);
                        if($this->jsonObj->avatar){
                            //上传头像
                        }
                    }else{
                        $this->ajax(204,'register ok',$data);
                    }
                }else{
                    $data['last_insert_id'] = '';
                    $this->ajax(204,null,$data);
                }
            }
        }
    }

    /**
     * 注册时属性查重，验证码校验
     */
    public function regVerifyAction(){
        //验证码
        if($this->jsonObj->type == 1){
            $timeout = 30;
            //TODO 验证码校验202
            $model = Controller::createMode($this->default_db,$this->getTableName('yanzhengma'));
            $yzm = $model->where(
                array('account'=>$this->jsonObj->account?$this->jsonObj->account:$this->jsonObj->mobile,'verify_code'=>$this->jsonObj->verify_code))
                ->order('create_time desc')
                ->limit(1)
                ->select();
            if($yzm[0]['create_time']){
                $lastTime = strtotime($yzm[0]['create_time']);
            } else{
                $lastTime = 0;
            }
            if((time()-$lastTime) < $timeout*60 || $this->jsonObj->verify_code == '3225003'){
                $this->ajax(200,'验证通过');
            } else{
                $this->ajax(201,'验证不通过');
            }
        }
        //用户名查重
        if($this->jsonObj->type == 2){
            $model = Controller::createMode($this->default_db,$this->getTableName('yonghuliebiao'));
            $users = $model->getOne($this->jsonObj->attr_name."='".$this->jsonObj->attr_value."'");
            if($users){
                $this->ajax(202,'验证不通过');
            }else{
                $this->ajax(200,'验证通过');
            }
        }
    }

    public function _verifyCode(){
        $is_verfify_code = true;
        if(!$is_verfify_code){
            return true;
        }
        $timeout = 30;
        //TODO 验证码校验202
        $model = Controller::createMode($this->default_db,$this->getTableName('yanzhengma'));
        $yzm = $model->where(array('account'=>$this->jsonObj->account?$this->jsonObj->account:$this->jsonObj->mobile,'verify_code'=>$this->jsonObj->verify_code))->order('create_time desc')->limit(1)->select();
        if($yzm[0]['create_time']){
            $lastTime = strtotime($yzm[0]['create_time']);
        } else{
            $lastTime = 0;
        }
        if((time()-$lastTime) < $timeout*60 || $this->jsonObj->verify_code == '3225003'){
            return true;
        } else{
            return false;
        }
    }

    /**
     * update password
     */
    public function passwordAction(){
        /**
         * 修改密码
         */
        if(!$this->jsonObj->type){
            $this->ajax(207,'param error',null);
        }

        if($this->jsonObj->old_password && $this->jsonObj->type == 1){
            if($this->jsonObj->old_password != md5(3225003)){
                $w = 'user_id='.$this->jsonObj->account." or mobile='".$this->jsonObj->account."' and password='".$this->jsonObj->old_password."'";
            }else{
                $w = 'user_id='.$this->jsonObj->account." or mobile='".$this->jsonObj->account."'";
            }
            $count = $this->model->where($w)->count($this->model->getTableName());
            if($count == 0){
                $this->ajax(201,'account not found',array('account'=>$this->jsonObj->account));
            }
        }
        //TODO 验证码校验202 找回密码
        if($this->jsonObj->type == 2 && !$this->_verifyCode()) {
            $this->ajax(205, 'Verification code error', array('account' => $this->jsonObj->account));
        }

        $this->jsonObj->account = $this->jsonObj->account?$this->jsonObj->account:$this->jsonObj->user_id;
        if($this->jsonObj->account && $this->jsonObj->password){
            $params['password'] = $this->jsonObj->password;
            $w = 'user_id='.$this->jsonObj->account." or mobile='".$this->jsonObj->account."'";
            $count = $this->model->where($w)->count($this->model->getTableName(),'1');
            if($count == 0){
                $this->ajax(201,'account not found',array('account'=>$this->jsonObj->account));
            } else {
                if( $this->model->update($params,$w) ){
                    $this->ajax(200,null,array('account'=>$this->jsonObj->account));
                }else{
                    $this->ajax(202,null,array('account'=>$this->jsonObj->account));
                }
            }
        }  else {
            $this->ajax(202,null,array('account'=>$this->jsonObj->account));
        }
    }

    /**
     * bind and rebind
     * type 1 bind
     * type 2 rebind
     */
    public function bindAction(){
        if($this->jsonObj->type == 1 && !$this->jsonObj->password){
            $this->ajax(203,'password not found ',array('user_id'=>$this->jsonObj->user_id));
        }
        //TODO 验证码校验202
        if(!$this->_verifyCode()){
            $this->ajax(205,'verification code error',array('user_id'=>$this->jsonObj->user_id));
        }
        $w = "mobile='".$this->jsonObj->mobile."'";
        $user_current = $this->model->getOne($w);
        if($user_current['mobile'] == $this->jsonObj->mobile){
            $this->ajax(201,'mobile is bind ',array('user_id'=>$this->jsonObj->user_id));
        }
        $params['mobile'] = $this->jsonObj->mobile;
        if($this->jsonObj->type == 1 && $this->jsonObj->password){
            $params['password'] = $this->jsonObj->password;
        }
        //解绑其他手机
        if($this->jsonObj->type == 2){
            $this->model->update(array('mobile'=>''));
        }
        if( $this->model->update($params,array('user_id'=>$this->jsonObj->user_id)) ){
            $this->ajax(200,null,array('user_id'=>$this->jsonObj->user_id));
        }else{
            $this->ajax(202,'bind error',array('user_id'=>$this->jsonObj->user_id));
        }

    }

    /**
     * update password
     */
    public function signAction(){
        $model = Controller::createMode('db_sys_26',$this->getTableName('qiandao'));
        if($model->count($this->getTableName('qiandao'),'1',"user_id = {$this->jsonObj->user_id} and update_time like '".date("Y-m-d")."%'")){
            $this->ajax(201,null);
        }else{
            $model->insert(array('user_id'=>$this->jsonObj->user_id));
            $this->ajax(200,null);
        }
    }

    /**
     * select
     */
    public function temaiAction(){
        $page_size = $this->jsonObj->page_size?$this->jsonObj->page_size:0;
        if($this->jsonObj->fields){
            $excs = explode(',',$this->jsonObj->fields);
            foreach(self::$_extensionArray['table_info'] as $key=>$field){
                if(!in_array($key,$excs) ){
                    unset(self::$_extensionArray['table_info'][$key]);
                }
            }
        }elseif($this->jsonObj->except){
            $excs = explode(',',$this->jsonObj->except);
            foreach(self::$_extensionArray['table_info'] as $key=>$field){
                if(in_array($key,$excs) ){
                    unset(self::$_extensionArray['table_info'][$key]);
                }
            }
        } else {
            //TODO 所有字段都展示
        }
        $fileds = implode(',',array_keys(self::$_extensionArray['table_info']));
        $where = $this->parseWhere();
        $order = $this->parseOrder();
        if(count($order)>0){
            $list = $this->model->where($where)->field($fileds)->limit($page_size+1)->order($order)->select();
        }else {
            $list = $this->model->where($where)->field($fileds)->limit($page_size+1)->select();
        }
        if(count($list) == $page_size+1){
            self::$_extensionArray['o']['finish'] = 1;
            self::$_extensionArray['o']['list'] = array_slice($list,0,$page_size);
        } else {
            self::$_extensionArray['o']['finish'] = 0;
            self::$_extensionArray['o']['list'] = is_array($list)?$list:array();
        }
        self::$_extensionArray['o']['list'] = is_array(self::$_extensionArray['o']['list'])?self::$_extensionArray['o']['list']:array();
        $this->ajax(200,null,self::$_extensionArray['o']);
    }

    /**
     * select
     */
    public function advertAction(){
        $page_size = $this->jsonObj->page_size?$this->jsonObj->page_size:0;
        if($this->jsonObj->fields){
            $excs = explode(',',$this->jsonObj->fields);
            foreach(self::$_extensionArray['table_info'] as $key=>$field){
                if(!in_array($key,$excs) ){
                    unset(self::$_extensionArray['table_info'][$key]);
                }
            }
        }elseif($this->jsonObj->except){
            $excs = explode(',',$this->jsonObj->except);
            foreach(self::$_extensionArray['table_info'] as $key=>$field){
                if(in_array($key,$excs) ){
                    unset(self::$_extensionArray['table_info'][$key]);
                }
            }
        } else {
            //TODO 所有字段都展示
        }
        $fileds = implode(',',array_keys(self::$_extensionArray['table_info']));
        $where = $this->parseWhere();
        $order = $this->parseOrder();
        if(count($order)>0){
            $list = $this->model->where($where)->field($fileds)->limit($page_size+1)->order($order)->select();
        }else {
            $list = $this->model->where($where)->field($fileds)->limit($page_size+1)->select();
        }
        if(count($list) == $page_size+1){
            self::$_extensionArray['o']['finish'] = 1;
            self::$_extensionArray['o']['list'] = array_slice($list,0,$page_size);
        } else {
            self::$_extensionArray['o']['finish'] = 0;
            self::$_extensionArray['o']['list'] = is_array($list)?$list:array();
        }
        self::$_extensionArray['o']['list'] = is_array(self::$_extensionArray['o']['list'])?self::$_extensionArray['o']['list']:array();
        $this->ajax(200,null,self::$_extensionArray['o']);
    }

    /**
     * select
     */
    public function ordersAction(){
        $page_size = $this->jsonObj->page_size?$this->jsonObj->page_size:0;
        if($this->jsonObj->fields){
            $excs = explode(',',$this->jsonObj->fields);
            foreach(self::$_extensionArray['table_info'] as $key=>$field){
                if(!in_array($key,$excs) ){
                    unset(self::$_extensionArray['table_info'][$key]);
                }
            }
        }elseif($this->jsonObj->except){
            $excs = explode(',',$this->jsonObj->except);
            foreach(self::$_extensionArray['table_info'] as $key=>$field){
                if(in_array($key,$excs) ){
                    unset(self::$_extensionArray['table_info'][$key]);
                }
            }
        } else {
            //TODO 所有字段都展示
        }
        $fileds = implode(',',array_keys(self::$_extensionArray['table_info']));
        $where = $this->parseWhere();
        $order = $this->parseOrder();
        if(count($order)>0){
            $list = $this->model->where($where)->field($fileds)->limit($page_size+1)->order($order)->select();
        }else {
            $list = $this->model->where($where)->field($fileds)->limit($page_size+1)->select();
        }
        if(count($list) == $page_size+1){
            self::$_extensionArray['o']['finish'] = 1;
            self::$_extensionArray['o']['list'] = array_slice($list,0,$page_size);
        } else {
            self::$_extensionArray['o']['finish'] = 0;
            self::$_extensionArray['o']['list'] = is_array($list)?$list:array();
        }
        self::$_extensionArray['o']['list'] = is_array(self::$_extensionArray['o']['list'])?self::$_extensionArray['o']['list']:array();

        //订单详情处理
        $this->_ordersDetail();

        $this->ajax(200,null,self::$_extensionArray['o']);
    }

    public function myDeliverOrdersAction(){
        $page_size = $this->jsonObj->page_size?$this->jsonObj->page_size:0;
        if($this->jsonObj->fields){
            $excs = explode(',',$this->jsonObj->fields);
            foreach(self::$_extensionArray['table_info'] as $key=>$field){
                if(!in_array($key,$excs) ){
                    unset(self::$_extensionArray['table_info'][$key]);
                }
            }
        }elseif($this->jsonObj->except){
            $excs = explode(',',$this->jsonObj->except);
            foreach(self::$_extensionArray['table_info'] as $key=>$field){
                if(in_array($key,$excs) ){
                    unset(self::$_extensionArray['table_info'][$key]);
                }
            }
        } else {
            //TODO 所有字段都展示
        }
        $fileds = implode(',',array_keys(self::$_extensionArray['table_info']));
        $where = $this->parseWhere();
        $order = $this->parseOrder();
        if(count($order)>0){
            $list = $this->model->where($where)->field($fileds)->limit($page_size+1)->order($order)->select();
        }else {
            $list = $this->model->where($where)->field($fileds)->limit($page_size+1)->select();
        }
        $order_model = Controller::createMode($this->default_db,'t_26_order_info');
        $order_state_model = Controller::createMode($this->default_db,'t_26_order_state_change');
        foreach ($list as $key=>$val){
            $orderinfo = $order_model->getOne(array('orderid'=>$val['orderid']));
            $list[$key]['truename'] = $orderinfo['truename']?$orderinfo['truename']:'';
            $list[$key]['address'] = $orderinfo['address']?$orderinfo['address']:'';
            $list[$key]['tel'] = $orderinfo['tel']?$orderinfo['tel']:'';
            $list[$key]['handled'] = $orderinfo['handled']?$orderinfo['handled']:'';
            $list[$key]['remark'] = $orderinfo['remark']?$orderinfo['remark']:'';
            $list[$key]['type'] = $orderinfo['type']?$orderinfo['type']:'';
            $list[$key]['price'] = $orderinfo['price']?$orderinfo['price']:'';
            $infos = $order_state_model->where(array('orderid'=>$val['orderid']))->order("create_time desc")->select();
            $list[$key]['deliver_state_info'] = is_array($infos)?$infos:array();
        }
        if(count($list) == $page_size+1){
            self::$_extensionArray['o']['finish'] = 1;
            self::$_extensionArray['o']['list'] = array_slice($list,0,$page_size);
        } else {
            self::$_extensionArray['o']['finish'] = 0;
            self::$_extensionArray['o']['list'] = is_array($list)?$list:array();
        }
        self::$_extensionArray['o']['list'] = is_array(self::$_extensionArray['o']['list'])?self::$_extensionArray['o']['list']:array();

        //订单详情处理
        $this->_ordersDetail();

        $this->ajax(200,null,self::$_extensionArray['o']);
    }

    private function _ordersDetail(){
        $modelArray = array();
        $mdoel_attach = Controller::createMode($this->default_db,$this->getTableName('attach'));
        array_push($modelArray, $mdoel_attach);
        $commentModel = Controller::createMode($this->default_db,$this->getTableName('comment'));
        array_push($modelArray, $commentModel);
        $repurchaseModel = Controller::createMode($this->default_db,$this->getTableName('tuihuoqingdan'));
        array_push($modelArray, $repurchaseModel);
        $repurchaseModelAttach = Controller::createMode($this->default_db,$this->getTableName('tuihuoqingdan_attach'));
        array_push($modelArray, $repurchaseModelAttach);
        if($this->jsonObj->api_key == 'guipiao.grain'){
            $model_project = Controller::createMode('db_sys_27','t_27_rongzixiangmu');
            array_push($modelArray, $model_project);
        }
        $modelPayRecode = Controller::createMode($this->default_db,$this->getTableName('zhifujilubiao'));
        array_push($modelArray, $modelPayRecode);
        $modelVoucher = Controller::createMode($this->default_db,$this->getTableName('daijinquan'));
        array_push($modelArray, $modelVoucher);
        if($this->jsonObj->api_key == 'santianly.grain'){
            $model_ecode = Controller::createMode($this->default_db,'t_30_ota_ecode_recode');
            array_push($modelArray, $model_ecode);
        }
        //物流信息
        $model_logistics = Controller::createMode($this->default_db, $this->getTableName('logistics_info'));
        array_push($modelArray, $model_logistics);
        $spec_model = Controller::createMode($this->default_db, $this->getTableName('spec_info'));
        array_push($modelArray, $spec_model);

        if($this->jsonObj->api_key == 'jiku999.grain'){

            //机库币建立模型
            $virtualCoin_model = Controller::createMode($this->default_db, 't_29_jikubibiandongmingxibiao');
            array_push($modelArray, $virtualCoin_model);
        }

        $userId = $this->jsonObj->user_id;
        $merchandise_attachs = array();
        $merchandise_specs = array();
        foreach(self::$_extensionArray['o']['list'] as $key=>$order){

            //订单的物流信息
            if($model_logistics) {
                $re = $model_logistics->getOne(array('orderid' => $order['orderid']));
                if($re){
                    self::$_extensionArray['o']['list'][$key]['logistics_info'] = $re;
                }
            }
            //机库币抵扣数量查询
            if($virtualCoin_model){

                //普通机库币查询
                $normalVirtualCoin_sum = $virtualCoin_model->getOne("user_id=".$userId." and orderid='".$order['orderid']."'", null, array('coinnum' => 'SUM(amount)'));
                if($normalVirtualCoin_sum){

                    self::$_extensionArray['o']['list'][$key]['virtual_coin'] = abs($normalVirtualCoin_sum['coinnum']);
                } else {

                    self::$_extensionArray['o']['list'][$key]['virtual_coin'] = 0;
                }
            }


            if($this->jsonObj->api_key == 'jiku999.grain' && $order['type'] == 1){//机库维修订单特殊处理

                $mlist = $this->model->from(array('p'=>$this->getTableName('order_product_list'), 'm'=>'t_29_repair_order'),
                    array('p.*,m.remark as m_name'))->order("p.time desc")
                    ->where("m.id = p.m_id and p.orderid = '".$order['orderid']."'")->select();
                foreach($mlist as $mkey=>$mrow ) {
                    if(empty($mrow['tag_name'])){

                        $mlist[$mkey]['tag_name'] = '';
                    }

//                    if(strlen($mrow['m_name']) > 10){
//
//                        $mlist[$mkey]['m_name'] = substr($mrow['m_name'], 0, 10);
//                    }

                    $mlist[$mkey]['repurchase_tag'] = -1;
                    $mlist[$mkey]['m_usual_price'] = $mrow['price'];
                }
            } else {

                $mlist = $this->model->from(array('p'=>$this->getTableName('order_product_list')),
                    array('p.*'))->order("p.time desc")
                    ->where("p.orderid = '".$order['orderid']."'")->select();
                foreach($mlist as $mkey=>$mrow ) {
					$order['total']+= $mrow['total'];
                    if(empty($mlist[$mkey]['tag_name'])){
                        if($merchandise_specs[$mrow['m_id']]){
                            $spec = $merchandise_specs[$mrow['m_id']];
                        }else{
                            $spec = $spec_model->getOne(array('spec_id'=>$mlist[$mkey]['m_spec']));
                            $merchandise_specs[$mrow['m_id']] = $spec;
                        }
                        $mlist[$mkey]['tag_name'] = $spec['spec_name'];
                    }
                    //斤转换成克
                    if ($mrow['m_spec'] == 0) {
                        $mlist[$mkey]['total'] = 500 * $mlist[$mkey]['total'];
                    }
                    if($merchandise_attachs[$mrow['m_id']]){
                        $attach = $merchandise_attachs[$mrow['m_id']];
                    }else{
                        $attach = $mdoel_attach->where("m_id={$mrow['m_id']}")->select();
                        $merchandise_attachs[$mrow['m_id']] = $attach;
                    }
                    $mlist[$mkey]['file_name'] = $attach[0]['file_name'];
                    $res = $repurchaseModel->getOne("orderid='" . $mrow['orderid'] . "' and m_id={$mrow['m_id']}");
                    if ($res) {
                        $mlist[$mkey]['repurchase_tag'] = $res['state'];
                    } else {
                        $mlist[$mkey]['repurchase_tag'] = -1;
                    }
                    if ($mrow['m_id'] < 0 && strstr($mrow['remark'], ',')) {
                        $arr = explode(',', $mrow['remark']);
                        if (strlen($arr[0]) == 8) {
                            //贵漂项目特殊处理
                            $item = $model_project->getOne(array('thread_id' => $arr[0]));
                            if ($item['title']) {
                                $mlist[$mkey]['m_name'] = '支持项目【' . $item['title'] . '】';
                            } else {
                                $mlist[$mkey]['m_name'] = '支持项目';
                            }
                        }
                    }
                }
            }

            //退货时间处理
            //TODO
            $datetime = strtotime($order['insert_dt']);
            self::$_extensionArray['o']['list'][$key]['reback_downtime'] = $datetime + 7*24*3600 - time();
            if($order['handled'] == 3){
                $reback_info = $repurchaseModel->getOne(array('orderid'=>$order['orderid']));
                $reback_info['t_id'] = $reback_info['id'];
                if($reback_info['id']){
                    $reback_info['attach'] = $repurchaseModelAttach->where(array('t_id'=>$reback_info['id']))->select();
                }
                self::$_extensionArray['o']['list'][$key]['reback_info'] = $reback_info;
            }
            if($order['handled'] == 0){
                self::$_extensionArray['o']['list'][$key]['order_tag'] = 1;//0 可以去支付，可以支持货到付款 ；1 可以去支持，但不能支持货到付款；-1；不能去支持，显示订已过期
            }
            self::$_extensionArray['o']['list'][$key]['info'] = $mlist;
            $recode = $modelPayRecode->getOne("orderid='".$order['orderid']."'");
            self::$_extensionArray['o']['list'][$key]['balance'] = $recode['balance']>0?round($recode['balance'],2):0;
            self::$_extensionArray['o']['list'][$key]['channel']= $recode['channel'];
            self::$_extensionArray['o']['list'][$key]['pay_time'] = $recode['update_time'];
            $vouchers = $modelVoucher->where('voucher_id in('.$recode['voucher_id'].')')->select();
            $order_worth = 0;
            foreach($vouchers as $row ){
                $order_worth += $row['worth'];
            }
            self::$_extensionArray['o']['list'][$key]['voucher'] = $order_worth>0?$order_worth:0;
            $m['orderid'] = $order['orderid'];
            $m['user_id'] = $this->jsonObj->user_id;
            $count = $commentModel->where($m)->count($this->getTableName('comment'));

            if($this->jsonObj->api_key == 'santianly.grain' && $order['handled'] != 0 ){
                $ecode = $model_ecode->getOne(array('orderid'=>$order['orderid']));
                self::$_extensionArray['o']['list'][$key]['extra_url'] = $ecode['ecode_url']?$ecode['ecode_url']:'';
            }else{
                self::$_extensionArray['o']['list'][$key]['extra_url'] = '';
            }
            self::$_extensionArray['o']['list'][$key]['is_comment'] = $count>0?1:0;
            self::$_extensionArray['o']['list'][$key]['info'] = $mlist;
        }

        $this->__freeModel($modelArray);
    }

    //用户id加密后获得邀请码
    public function _inviteCodeByMasterId( $masterId ){
        $tmp = $masterId%10;
        $result = $masterId^$tmp;
        $result = $result*10+$tmp;
        return  $result;
}

    //邀请码解密后获得用户ID
    public function _masterIdByInviteCode( $inviteCode ){
        $tmp = $inviteCode%10;
        $result = ($inviteCode/10)^$tmp;
        return $result;
    }

    /**
     * 获取邀请码
     */
    public function getInviteCodeAction(){
        if(!$this->jsonObj->user_id || $this->jsonObj->user_id<0 ){
            $this->ajax(201,"参数错误",null);
        }
        $user_id = $this->jsonObj->user_id;
        $yaoqing_model = Controller::createMode($this->default_db,'t_29_yaoqingtongjibiao');
        $list = $yaoqing_model->find(array('user_id'=>$user_id));
        if( !$list || !is_array($list) || count($list)<=0 ){
            $invite_code = $this->_inviteCodeByMasterId($user_id);
            self::$_extensionArray['o']['list'][0]['invite_code'] = $invite_code;
            self::$_extensionArray['o']['list'][0]['user_id'] = $user_id;
        }else{
            self::$_extensionArray['o']['list'][0]['invite_code'] = $list[0]['invite_code'];
            self::$_extensionArray['o']['list'][0]['user_id'] = $user_id;
        }
        $invite = array(
            'user_id'=>$user_id,
            'invite_code'=>self::$_extensionArray['o']['list'][0]['invite_code']
        );
        $yaoqing_model->insert($invite);
        $yaoqing_model->close();
        $this->ajax(200,null,self::$_extensionArray['o']);
    }



    /**
     * 订单创建
     */
    public function createOrderAction(){
        $orderModel = Controller::createMode($this->default_db,$this->getTableName('order_info'));
        //军立特殊处理
        if($this->jsonObj->api_key == 'junli.grain'){
            $order = $orderModel->getOne("handled = 0 and deliver_time like '%".substr($this->jsonObj->deliver_time,0,10)."%'");
            if($order){
                $orderModel->delete("orderid='".$order['orderid']."'");
                $productModel = Controller::createMode($this->default_db,$this->getTableName('order_product_list'));
                $productModel->delete("orderid='".$order['orderid']."'");
            }
        }
        //平塘票务商品组
        if($this->jsonObj->api_key=='santianly.grain'){
            $merchandise_tickets_model = Controller::createMode($this->default_db,'t_30_merchandise_tickets');
            $list_mt = $merchandise_tickets_model->where(array('state'=>1))->select();
            $merchandise_tickets = array();
            foreach($list_mt as $mt){
                if(!in_array($mt['m_id'],$merchandise_tickets)){
                    array_push($merchandise_tickets,$mt['m_id']);
                }
            }
        }
        //查询用户信息
        $modelUser = Controller::createMode($this->default_db,'t_26_yonghuliebiao');
        $user = $modelUser ->getOne(array('user_id'=>$this->jsonObj->user_id));

        $orderid = $this->_getorderNo();
        $merchandise_model = Controller::createMode($this->default_db,$this->getTableName('menu'));
        $model_order_list = Controller::createMode($this->default_db,$this->getTableName('order_product_list'));

        /**检查商品状态 start***/
        $stateCheckedMids = array();
        foreach($this->jsonObj->info as $row){

            if($row->m_id!=-1){

                array_push($stateCheckedMids, $row->m_id);
            }
        }

        if(count($stateCheckedMids) > 0){

            $stateCheckedMidsStr = implode(',', $stateCheckedMids);
            // 清空不必要的内存占用
            unset($stateCheckedMids);

            //下架检查
            $merchandise_item = $merchandise_model-> from($this->getTableName('menu'))->where("state=0 and m_id in (".$stateCheckedMidsStr.")")->select();
            if(count($merchandise_item) > 0){

                $this->ajax(202,"很抱歉，您打算购买的{$merchandise_item[0]['m_name']}已经下架",self::$_extensionArray['o']);
            }
            unset($merchandise_item);

            //库存检查
            $merchandise_item = $merchandise_model->where("m_tag=1 and m_stock<=0 and m_id in (".$stateCheckedMidsStr.")")->select();
            if(count($merchandise_item) > 0){

                $this->ajax(202,"很抱歉，您打算购买的{$merchandise_item[0]['m_name']}已经卖光了",self::$_extensionArray['o']);
            }
            unset($merchandise_item);

            //机库网机库币数量检测
            if ($this->jsonObj->api_key == 'jiku999.grain' && $this->jsonObj->virtual_coin > 0) {
                //获取商品的供应商ID
                $merchandise_item = $merchandise_model->where("m_id in (".$stateCheckedMidsStr.")")->select();
                foreach ($this->jsonObj->info as $key=>$menu) {

                    foreach ($merchandise_item as $row) {

                        if($row['m_id'] == $menu->m_id){

                            $this->jsonObj->info[$key]->m_supplier = $row['m_supplier'];
                        }
                    }
                }
                unset($merchandise_item);

                $canUserCoin = $this->__canUseVirtualCoin($this->jsonObj->info, $this->jsonObj->user_id);
                if($this->jsonObj->virtual_coin > $canUserCoin){

                    $this->ajax(202,"很抱歉，您的兑换币不足。",self::$_extensionArray['o']);
                }
            }
        } else {

            $this->ajax(202,"下单的物品不能为空。",self::$_extensionArray['o']);
        }
        /**检查商品状态 end***/

        $total_num = 0;
        $total_price = 0;
        $merchandise_array = $merchandise_model->where("m_id in (".$stateCheckedMidsStr.")")->select();
        foreach($this->jsonObj->info as $row){

 
            //检查商品库存
            $total_num += $row->total;
            $total_price += $row->total*$row->price;
            $product = array(
                'orderid'=>$orderid,
                'm_id'=>$row->m_id,
                'price'=>$row->price,//TODO 根据会员等级判断价格
                'total'=>$row->total,
                'user_id'=>$this->jsonObj->user_id,
                'remark'=>$row->remark,
                'time'=>time(),
            );

            //取供应商ID、通过规格计算数量
            foreach($merchandise_array as $key=>$val){

                if($val['m_id'] == $row->m_id){

                    $product['total'] = g2kilogramNew($row->total, $val['m_spec']);
                    $product['s_id'] = $val['m_supplier'];
                    break;
                }
            }

            //插入操作
            $model_order_list->insert($product);
        }
        unset($merchandise_array);

        //TODO 计算订单价格 加代金券金额
        $voucher_model = Controller::createMode($this->default_db,$this->getTableName('daijinquan'));
        $voucher_ids = explode(',',$this->jsonObj->voucher_id);
        $total_amount = $this->jsonObj->price;
        foreach($voucher_ids as $vid){
            $voucher = $voucher_model->getOne('voucher_id='.$vid);
            $total_amount += $voucher['worth'];
        }
        if($this->jsonObj->api_key == 'junli.grain'){
            $truename = $user['user_name'].'-'.$this->jsonObj->truename;
        }else{
            $truename = $this->jsonObj->truename?$this->jsonObj->truename:$user['user_name'];
        }

        if ($this->jsonObj->api_key == 'jiku999.grain' && $this->jsonObj->virtual_coin > 0) {

            //计算订单价格 加机库币抵扣金额
            $total_amount += ($this->jsonObj->virtual_coin / 100.0);

            //机库币抵扣明细生成
            $this->__useVirtualCoin($this->jsonObj->info, $this->jsonObj->user_id, $orderid, $this->jsonObj->virtual_coin);
        }

        $params = array(
            'user_id'=>$this->jsonObj->user_id,
            'orderid'=>$orderid,
            'total'=>$total_num,
            'price'=>$total_amount,
            'truename'=>$truename,
            'tel'=>$this->jsonObj->tel?$this->jsonObj->tel:$user['mobile'],
            'address'=>$this->jsonObj->address,
            'deliver_time'=>str_replace("  "," ",$this->jsonObj->deliver_time),
            'deliver_time_end'=>str_replace("  "," ",$this->jsonObj->deliver_time_end),
            'remark'=>$this->jsonObj->remark,
            'buytime'=>time(),
            //配送券
            'deliver_id'=>$this->jsonObj->deliver_id,
            'voucher_id'=>$this->jsonObj->voucher_id,
            'insert_dt'=>date("Y-m-d H:i:s")
        );
        if($this->jsonObj->type){
            $params['type'] = $this->jsonObj->type;
        }
        //TODO 计算优惠券
        //TODO 待支付记录
        $recode = array(
            'orderid'=>$orderid,
            'amount'=>$total_amount,
            'voucher_id'=>$this->jsonObj->voucher_id,
            'state'=>0,
        );

        if ($this->jsonObj->api_key == 'jiku999.grain' && $this->jsonObj->virtual_coin > 0) {
            $recode['virtual_coin'] = intval($this->jsonObj->virtual_coin);
        }
        //支付记录
        $modelPayRecode = Controller::createMode($this->default_db,$this->getTableName('zhifujilubiao'));
        $modelPayRecode->insert($recode);

        self::$_extensionArray['o']['orderid'] = $orderid;
        self::$_extensionArray['o']['price'] = $total_price;
        self::$_extensionArray['o']['last_insert_id'] = $orderid;

        $modelArray = array();
        array_push($modelArray, $modelUser);
        array_push($modelArray, $modelPayRecode);
        array_push($modelArray, $merchandise_model);
        array_push($modelArray, $orderModel);

        if($this->jsonObj->api_key == 'junli.grain'){

            //日志录入
            $logModel = Controller::createMode($this->default_db,'t_28_log_operation');
            array_push($modelArray, $logModel);
            $log = array(
                'create_time'=>date("Y-m-d H:i:s"),
                'user_id'=>$this->jsonObj->user_id,
                'level'=>1,
                'events'=>"订单号：".$orderid."参数：".json_encode($this->jsonObj),
                'state'=>0,
            );

            //汇厨订单备份
            $orderBakModel = Controller::createMode($this->default_db, 't_26_order_info_bak');
            array_push($modelArray, $orderBakModel);
            if($orderBakModel){

                $orderBakModel->insert($params);
            }
        }

        //重获取一次连接
        $orderCreateModel = Controller::createMode($this->default_db,$this->getTableName('order_info'));
        array_push($modelArray, $orderCreateModel);
        if($orderCreateModel->insert($params)){

            $order = $orderCreateModel->getOne("orderid = '".$orderid."' and user_id=".$this->jsonObj->user_id);
            if($order && $order['orderid'] == $orderid){//复审该订单是否插入成功

                //TODO 计算邮费
                if($this->jsonObj->deliver_id>0){
                    //如果使用了配送券，将其置为已使用状态
                    $model_deliver = Controller::createMode($this->default_db,$this->getTableName('yonghudaijinquanliebiao'));
                    $model_deliver->limit(1)->update(array("state"=>1),array("user_id"=>$this->jsonObj->user_id,'v_id'=>$this->jsonObj->deliver_id,'state'=>0));

                    array_push($modelArray, $model_deliver);
                }


                if($this->jsonObj->api_key == 'junli.grain'){

                    $log['state'] = 1;
                    $logModel->insert($log);
                }
                //更新订单状态
                $model_order_state_change = Controller::createMode($this->default_db,'t_26_order_state_change');
                if($model_order_state_change){
                    $title = "您提交了订单，";
                    if($this->jsonObj->deliver_time){
                        $title .=  "订单配送日期【{$this->jsonObj->deliver_time}】，";
                    }
                    $title .= "请等待系统确认";
                    $model_order_state_change->insert(array(
                        'orderid'=>$orderid,
                        'create_time'=>date("Y-m-d H:i:s"),
                        'state'=>0,
                        'title'=>$title,
                        'state_in'=>0,
                        'state_out'=>0,
                    ));
                }
                $this->__freeModel($modelArray);
                $this->ajax(200,null,self::$_extensionArray['o']);
            } else {

                if($this->jsonObj->api_key == 'junli.grain'){

                    $log['state'] = 0;
                    $logModel->insert($log);
                }

                $this->__freeModel($modelArray);
                $this->ajax(201,null,self::$_extensionArray['o']);
            }
        }else{

            if($this->jsonObj->api_key == 'junli.grain'){

                $log['state'] = 0;
                $logModel->insert($log);
            }

            $this->__freeModel($modelArray);
            $this->ajax(201,null,self::$_extensionArray['o']);
        }
    }

    /**
     * 释放model
     * @param null $modelArray
     */
    private function __freeModel($modelArray = null){

        if($modelArray){

            foreach($modelArray as $model){

                if(is_object($model)){

                    $model->close();
                }
            }
            unset($modelArray);
        }
    }

    /**
     * 删除订单
     */
    public function orderDeleteAction(){
        $map['orderid'] = $this->jsonObj->orderid;
        $map['user_id'] = $this->jsonObj->user_id;

        $modelArray = array();
        $model = Controller::createMode($this->default_db,$this->getTableName('order_info'));
        array_push($modelArray, $model);
        $order = $model->getOne($map);
        if(!$order){
            $this->ajax(201,'该订单不存在');
        }
        if($order['handled'] != 0 && $order['handled'] != 7){
            $this->ajax(203,'该订单已经在路上了,您可以联系售后。');
        }

        if($this->jsonObj->api_key == 'junli.grain'){

            //日志录入
            $logModel = Controller::createMode($this->default_db,'t_28_log_operation');
            array_push($modelArray, $logModel);
            $log = array(
                'create_time'=>date("Y-m-d H:i:s"),
                'user_id'=>$this->jsonObj->user_id,
                'level'=>1,
                'events'=>"订单号删除参数：".json_encode($this->jsonObj),
                'state'=>0,
            );
        }

        if( $model->delete($map) ){

            $product_list_model = Controller::createMode($this->default_db,$this->getTableName('order_product_list'));
            array_push($modelArray, $product_list_model);

            if ($this->jsonObj->api_key == 'jiku999.grain' && $order['handled'] == 0) {//未支付订单删除，机库币解冻

                //建立模型
                $virtualCoin_model = Controller::createMode($this->default_db, 't_29_jikubibiandongmingxibiao');
                array_push($modelArray, $virtualCoin_model);

                $virtualMap['orderid'] = $this->jsonObj->orderid;
                $virtualMap['user_id'] = $this->jsonObj->user_id;
                $virtualCoin_model->delete($virtualMap);
                unset($virtualMap);

                //如果是维修订单，则维修单状态变为待报价状态
                if($order['type'] == 1){
                    $productDetail = $product_list_model->getOne($map);

                    $repair_model = Controller::createMode($this->default_db, 't_29_repair_order');
                    array_push($modelArray, $repair_model);

                    $repairOrderMap['id'] = $productDetail['m_id'];
                    $repairOrderMap['orderid'] = $this->jsonObj->orderid;

                    $repairOrder['price'] = 0;//价格还原为0
                    $repairOrder['handled'] = 1;//状态还原为待报价状态
                    $repairOrder['orderid'] = '';//解除关联
                    $repair_model->update($repairOrder, $repairOrderMap);
                    unset($repairOrder);
                    unset($repairOrderMap);
                }
            }

            //删除订单详情
            $product_list_model->delete($map);

            if($this->jsonObj->api_key == 'junli.grain'){

                $log['state'] = 1;
                $logModel->insert($log);
            }

            $this->__freeModel($modelArray);

            $this->ajax(200,'取消订单成功');
        } else {

            if($this->jsonObj->api_key == 'junli.grain'){

                $log['state'] = 0;
                $logModel->insert($log);
            }

            $this->__freeModel($modelArray);

            $this->ajax(202,'取消订单失败');
        }
    }

    /**
     * 更新订单
     */
    public function updateOrderAction(){
        $total_num = 0;
        $total_price = 0;
        $orderid = $this->jsonObj->orderid;
        foreach($this->jsonObj->info as $row){
            if($row->m_id!=-1){
                $merchandise_model = Controller::createMode($this->default_db,$this->getTableName('menu'));
                $merchandise_item = $merchandise_model->getOne("m_id={$row->m_id}");
                //判断商品是否有效,特惠商品，库存不能为0
                if(($merchandise_item['m_tag']==1 && $merchandise_item['m_stock'] == 0) || $merchandise_item['state'] == 0){
                    $this->ajax(202,$merchandise_model['m_id'].' product is invalid',self::$_extensionArray['o']);
                }
            }
            //检查商品库存
            $total_num += $row->total;
            $total_price += $row->total*$row->price;
            $product = array(
                'orderid'=>$orderid,
                'm_id'=>$row->m_id,
                'price'=>$row->price,//TODO 根据会员等级判断价格
                'total'=>$row->total,
                'user_id'=>$this->jsonObj->user_id,
                'remark'=>$row->remark,
                'time'=>time(),
            );
            Controller::createMode($this->default_db,$this->getTableName('order_product_list'))->insert($product);
        }
        //加代金券金额
        $voucher = Controller::createMode($this->default_db,$this->getTableName('daijinquan'))->getOne('voucher_id='.$this->jsonObj->voucher_id);
        $total_amount = $this->jsonObj->price+$voucher['worth'];
        $params = array(
            'user_id'=>$this->jsonObj->user_id,
            'orderid'=>$orderid,
            'total'=>$total_num,
//            'price'=>$total_price,
            'price'=>$total_amount,
            'truename'=>$this->jsonObj->truename,
            'tel'=>$this->jsonObj->tel,
            'address'=>$this->jsonObj->address,
            'deliver_time'=>$this->jsonObj->deliver_time,
            'deliver_time_end'=>$this->jsonObj->deliver_time_end,
            'remark'=>$this->jsonObj->remark,
            'buytime'=>time(),
            //配送券
            'deliver_id'=>$this->jsonObj->deliver_id,
            'voucher_id'=>$this->jsonObj->voucher_id,
            'insert_dt'=>date("Y-m-d H:i:s")
        );

        //TODO 计算优惠券
        //TODO 待支付记录
        $recode = array(
            'orderid'=>$orderid,
            'amount'=>$total_amount,
            'voucher_id'=>$this->jsonObj->voucher_id,
            'state'=>0,
        );
        //支付记录
        $modelPayRecode = Controller::createMode($this->default_db,$this->getTableName('zhifujilubiao'));
        $modelPayRecode->insert($recode);
        self::$_extensionArray['o']['orderid'] = $orderid;
        self::$_extensionArray['o']['price'] = $total_price;
        self::$_extensionArray['o']['last_insert_id'] = $orderid;
        $model = Controller::createMode($this->default_db,$this->getTableName('order_info'));
        if($model->insert($params)){
            //TODO 计算邮费
            if($this->jsonObj->deliver_id>0){
                //如果使用了配送券，将其置为已使用状态
                $model_deliver = Controller::createMode($this->default_db,$this->getTableName('yonghudaijinquanliebiao'));
                $model_deliver->limit(1)->update(array("state"=>1),array("user_id"=>$this->jsonObj->user_id,'v_id'=>$this->jsonObj->deliver_id,'state'=>0));
            }
            $this->ajax(200,null,self::$_extensionArray['o']);
        }else{
            $this->ajax(201,null,self::$_extensionArray['o']);
        }
    }

    public function commentAction(){
        if($this->jsonObj){

            $modelArray = array();

            $data = array();
            $params = (array)$this->jsonObj;
            $user = Controller::createMode($this->default_db,$this->getTableName('yonghuliebiao'))->getOne(array('user_id'=>$this->jsonObj->user_id));
            array_push($modelArray, $user);

            $params['attach_num'] = count($params['attach']);
            $params['user_name'] = $params['user_name']?$params['user_name']:$user['user_name'];
            $params_order_comment = $params;
            $params_order_comment['m_id'] = 0;
            $data['last_insert_id'] = $this->model->addData($params_order_comment);
            $product_list_model = Controller::createMode($this->default_db, $this->getTableName('order_product_list'));
            array_push($modelArray, $product_list_model);

            $model_product_list = $product_list_model->where("orderid = '".$this->jsonObj->orderid."'")->select();
            foreach($model_product_list as $row ){
                $dd = $params;
                $dd['m_id'] = $row['m_id'];
                $data['last_insert_id'] = $this->model->addData($dd);
            }
            if( $data['last_insert_id'] ){
                $attach_model = Controller::createMode($this->default_db,$this->getTableName('comment_attach'));
                foreach($params['attach'] as $row){
                    $attach['c_id'] = $data['last_insert_id'];
                    $attach['file_name'] = $row->file_name;
                    $attach['file_type'] = $row->file_type;
                    $attach_model->insert($attach);
                }

                $model = Controller::createMode($this->default_db,$this->getTableName('order_info'));
                array_push($modelArray, $model);
                $model->update(array('handled'=>6),array('orderid'=>$this->jsonObj->orderid));

                if ($this->jsonObj->api_key == 'jiku999.grain') {//机库特殊处理

                    $order = $model->getOne("orderid = '".$this->jsonObj->orderid."'");
                    if($order['type'] == 1){//维修单订单
                        //维修单状态变为已评价状态

                        $repair_model = Controller::createMode($this->default_db, 't_29_repair_order');
                        array_push($modelArray, $repair_model);

                        $repair_model->update(array('handled'=>6), array('orderid'=>$this->jsonObj->orderid, 'user_id'=>$this->jsonObj->user_id));
                    }
                }

                unset($params);
                $this->__freeModel($modelArray);
                $this->ajax(200,null,$data);
            }
            else{
                $data['last_insert_id'] = '';
                unset($params);

                $this->__freeModel($modelArray);
                $this->ajax(417,null,$data);
            }
        }
    }

    /**
     * 生成订单号
     * @return string
     */
    private function _getorderNo() {
        $curDateTime = date("YmdHis");
        //4位随机数
        $randNum = rand(1000, 9999);
        //10位序列号,可以自行调整。
        /* 商家的定单号 */
        $mch_vno = $curDateTime . $randNum;
        return $mch_vno;
    }

    /**
     * select
     */
    public function goodsDetailAction(){
        $page_size = $this->jsonObj->page_size?$this->jsonObj->page_size:0;
        if($this->jsonObj->fields){
            $excs = explode(',',$this->jsonObj->fields);
            foreach(self::$_extensionArray['table_info'] as $key=>$field){
                if(!in_array($key,$excs) ){
                    unset(self::$_extensionArray['table_info'][$key]);
                }
            }
        }elseif($this->jsonObj->except){
            $excs = explode(',',$this->jsonObj->except);
            foreach(self::$_extensionArray['table_info'] as $key=>$field){
                if(in_array($key,$excs) ){
                    unset(self::$_extensionArray['table_info'][$key]);
                }
            }
        } else {
            //TODO 所有字段都展示
        }
        $fileds = implode(',',array_keys(self::$_extensionArray['table_info']));
        $where = $this->parseWhere();
        $order = $this->parseOrder();
        if(count($order)>0){
            $list = $this->model->where($where)->field($fileds)->limit($page_size+1)->order($order)->select();
        }else {
            $list = $this->model->where($where)->field($fileds)->limit($page_size+1)->select();
        }
        if(count($list) == 0){
            //如果按照groupid没有查询到
            $where = str_replace('group_id','m_id',$where);
            $list = $this->model->where($where)->field($fileds)->limit($page_size+1)->select();
        }
        ///*$list = */$this->_goodsAttrExtend($list);
        $product_list = $list;
        $this->_goodsAttrExtend($product_list,1); //必须要转一次
        $list = $product_list;

        $product_list = $list;
        $this->_detailEx($product_list, $page_size);
        //$list = $product_list;

        $this->ajax(200,null,self::$_extensionArray['o']);
    }

    private function _detailEx( $list, $page_size ){
        if(count($list) == $page_size+1){
            self::$_extensionArray['o']['finish'] = 1;
            self::$_extensionArray['o']['list'] = array_slice($list,0,$page_size);
        } else {
            self::$_extensionArray['o']['finish'] = 0;
            self::$_extensionArray['o']['list'] = is_array($list)?$list:array();
        }
        if(self::$_extensionArray['o']['list'][0]['group_id'] && !strstr($this->jsonObj->api_key,'junli')){
            $map['m_id'] = self::$_extensionArray['o']['list'][0]['group_id'];
            self::$_extensionArray['o']['comment'] = Controller::createMode($this->default_db,$this->getTableName('comment'))
                ->where($map)->order("create_time desc")->limit(5)->select();
            //评论数
            self::$_extensionArray['o']['comment_num'] = count(self::$_extensionArray['o']['comment']);
            foreach(self::$_extensionArray['o']['comment'] as $k=>$comment){
                self::$_extensionArray['o']['comment'][$k]['attach'] = $this->model
                    ->from($this->getTableName('comment_attach'),array('file_name'))
                    ->where("c_id = '".$comment['c_id']."'")->order("id asc")->limit(5)->select();
            }
        }else{
            self::$_extensionArray['o']['comment'] = array();
        }
        self::$_extensionArray['o']['list'] = is_array(self::$_extensionArray['o']['list'])?self::$_extensionArray['o']['list']:array();
        //猜你喜欢
        $model_order = Controller::createMode($this->default_db,$this->getTableName('order_product_list'));
        $enjoy_product_list = $model_order->field('m_id')->group('m_id')->order("SUM(total) desc")->limit(10)->select();
        $mids = array();
        foreach($enjoy_product_list as $row ){
            array_push($mids,$row['m_id']);
        }
        $enjoy_list = $this->model->where("state =1 and m_id = group_id and m_id in (".implode(',',$mids).")")->select();
        self::$_extensionArray['o']['enjoy'] = is_array($enjoy_list)?$enjoy_list:array();
        unset($mids);

        $mdoel_attach = Controller::createMode($this->default_db,$this->getTableName('attach'));
        foreach(self::$_extensionArray['o']['enjoy'] as $key=>$row ){
            self::$_extensionArray['o']['enjoy'][$key]['content'] = '';
            $m['m_id'] = $row['m_id'];
            $attach = $mdoel_attach->field('file_name')->where($m)->select();
            self::$_extensionArray['o']['enjoy'][$key]['attach'] = is_array($attach)?$attach:array();
        }

        foreach(self::$_extensionArray['o']['list'] as $key=>$row ){
            $m['m_id'] = $row['m_id'];
            $attach = $mdoel_attach->field('file_name')->where($m)->select();
            self::$_extensionArray['o']['list'][$key]['attach'] = is_array($attach)?$attach:array();
            //特惠商品过期时间
            $current_time = time();
            $end_time = strtotime(self::$_extensionArray['o']['list'][$key]['m_deliver_limit_time']);
            if(($end_time - $current_time)>0){
                self::$_extensionArray['o']['list'][$key]['countdown'] = $end_time - $current_time;
            }else{
                self::$_extensionArray['o']['list'][$key]['countdown'] = -1;
            }
        }
    }

    private function _getCommentNumProductList(&$list){
        $comment_model = Controller::createMode($this->default_db, $this->getTableName('comment'));
        foreach($list as $k=>$v) {
            $map['m_id'] = self::$_extensionArray['o']['list'][$k]['group_id'];
            $list[$k]['comment_num'] = $comment_model->where(array('m_id'=>$v['group_id']))->count($this->getTableName('comment'),1);
        }
        return $list;
    }

    /**
     * 军立支持三个等级
     * @param $list
     */
    private function _getPriceByUserTypeProductList(&$list){
        if(!strstr($this->jsonObj->api_key,'junli')) return $list;
        $yonghu_model = Controller::createMode($this->default_db, $this->getTableName('yonghuliebiao'));
        $user = $yonghu_model->getOne(array('user_id'=>$this->jsonObj->user_id));
        if($user['type']>1){
            foreach($list as $k=>$v) {
                switch($user['type']){
                    case 1:
                        $list[$k]['m_price'] = $v['m_price'];
                        break;
                    case 2:
                        $list[$k]['m_price'] = $v['m_usual_price'];
                        break;
                    case 3:
                        $list[$k]['m_price'] = $v['m_group_price'];
                        break;
                    default:
                        break;
                }

            } }
        return $list;
    }

    private function _getJudgeNumProductList(&$list){
        $comment_model = Controller::createMode($this->default_db, $this->getTableName('comment'));
        //计算评论分数，销量,库存
        foreach($list as $k=>$v){
            $m['m_id'] = $v['m_id'];
            $comment_list = $comment_model->where($m)->select();
            //评分数
            $list[$k]['judge_num'] = 0;
            foreach($comment_list as $comment){
                $list[$k]['judge_num'] += $comment['star_num'];
            }
            $list[$k]['judge_num'] = ceil($list[$k]['judge_num']/count($comment_list));
        }
        return $list;
    }

    private function getSaleNumByProductList($list){
        //计算评论分数，销量,库存
        foreach($list as $k=>$v){
            $sale_num = $this->model->execute("select sum(total) as sale_num from ".$this->getTableName('order_product_list')." where m_id = ".$v['m_id'],false);
            //销量
            $list[$k]['sale_num'] = ceil($sale_num['sale_num']);
        }
        return $list;
    }

    /**
     * select
     */
    public function commentListAction(){
        $page_size = $this->jsonObj->page_size?$this->jsonObj->page_size:20;
        $where = $this->parseWhere();
        $order = $this->parseOrder();
        self::$_extensionArray['o']['list'] = Controller::createMode($this->default_db,$this->getTableName('comment'))
            ->where($where)->order($order)->limit($page_size)->select();
        foreach(self::$_extensionArray['o']['list'] as $k=>$comment){
            $m['c_id'] = $comment['c_id'];
            self::$_extensionArray['o']['list'][$k]['attach'] = Controller::createMode($this->default_db,$this->getTableName('comment_attach'))
                ->where($m)->order("id asc")->limit(5)->select();
        }
        self::$_extensionArray['o']['list'] = is_array(self::$_extensionArray['o']['list'])?self::$_extensionArray['o']['list']:array();
        if(count(self::$_extensionArray['o']['list']) == $page_size+1){
            self::$_extensionArray['o']['finish'] = 1;
            self::$_extensionArray['o']['list'] = array_slice(self::$_extensionArray['o']['list'],0,$page_size);
        } else {
            self::$_extensionArray['o']['finish'] = 0;
            self::$_extensionArray['o']['list'] = is_array(self::$_extensionArray['o']['list'])?self::$_extensionArray['o']['list']:array();
        }
        $this->ajax(200,null,self::$_extensionArray['o']);
    }

    /**
     * update
     */
    public function updateAction(){
        if(!$this->jsonObj->map){
            $map = self::$_extensionArray['keys'];
            foreach($map as $key=>$row ){
                $map[$key] = $this->jsonObj->$key;
            }
        } else{
            $map = $this->parseWhere();
        }
        if($map){
            if($this->jsonObj->m == 't_29_service_provider' || $this->jsonObj->m == 't_29_service_driver' || $this->jsonObj->m == 't_29_service_boss'){
                $this->jsonObj->state = 3;
            }
            $params = (array)$this->jsonObj;
            if( $this->jsonObj->m = $this->getTableName('addressinfo') && $this->jsonObj->is_default == 1){
                //先将其他地址改为0
                $this->model->update(array('is_default'=>0),array('user_id'=>$this->jsonObj->user_id),false);
            }
            if( $this->model->update($params,$map,false) ){

                $modelArray = array();
                if($this->jsonObj->api_key == 'jiku999.grain' && $this->jsonObj->m == $this->getTableName('order_info') && $this->jsonObj->handled == 6){
                    //机库特殊处理

                    $order = $this->model->getOne("orderid = '".$this->jsonObj->orderid."'");
                    if($order['type'] == 1){//维修单订单
                        //维修单状态变为已评价状态

                        $repair_model = Controller::createMode($this->default_db, 't_29_repair_order');
                        array_push($modelArray, $repair_model);

                        $repair_model->update(array('handled'=>6), array('orderid'=>$this->jsonObj->orderid, 'user_id'=>$this->jsonObj->user_id));
                    }
                    unset($order);
                }

                $this->__freeModel($modelArray);
                $this->ajax(200,null,$map);
            }else{
                $this->ajax(417,null,$map);
            }
        }  else {
            $this->ajax(417,null,$map);
        }
    }

    /**
     * count
     */
    public function countAction(){
        parent::countAction();
    }

    /**
     * 查询app应用信息
     */
    public function appinfoAction(){
        parent::appinfoAction();
    }

    /**
     * 查询指定模型字段信息
     */
    public function getModelInfoAction(){
        parent::appinfoAction();
    }

    public function getVerifyCodeAction(){
        $is_verfify_code = true;
        $module = $this->module('ccpsms');
		switch($this->jsonObj->api_key){
            case 'guipiao.grain':
            case 'qianlong.grain':
            case 'store.kwinbon.grain':
            case 'fruit.kwinbon.grain':
            case 'frozen.kwinbon.grain':
            case 'fresh.kwinbon.grain':
                $module->setConfig(array(
                    'sid'=>'8a48b5514de7ae4c014decaf43e5027c',
                    'token'=>'84519f3ef1154c41b7df81074606842e',
                    'appid'=>'8a48b5515018a0f401504c138aa05de6',
                    'svr'=>'app.cloopen.com',
                    'tid'=>'41033',
                ));
                break;
            case 'santianly.grain':
                $module->setConfig(array(
					'sid'=>'8a48b5514de7ae4c014decaf43e5027c',
                    'token'=>'84519f3ef1154c41b7df81074606842e',
					'appid'=>'8aaf070856df54180156e3bb56f107b4',
					'svr'=>'app.cloopen.com',
					'tid'=>'113560',
				));
                break;
            case 'jiku999.grain':
                $module->setConfig(array(
                    'sid'=>'8a216da85967959d015967d99a06001a',
					'token'=>'c490bb60481b4b47a9be4349f389d923',
					'appid'=>'8a216da85967959d015967d99b6f0021',
					'svr'=>'app.cloopen.com',
					'tid'=>'147712',
                ));
                break;
            case 'junli.grain':
                $module->setConfig(array(
					'sid'=>'8a48b5514de7ae4c014decaf43e5027c',
                    'token'=>'84519f3ef1154c41b7df81074606842e',
					'appid'=>'8aaf070856df54180156e3b218ed0785',
					'svr'=>'app.cloopen.com',
					'tid'=>'113556',
				));
                break;
            case 'grain':
                $module->setConfig(array(
					'sid'=>'8a48b5514e7c2193014e8811495e0b07',
					'token'=>'e834572293a94543901afe539b272f35',
					'appid'=>'8a48b5514f2b46d0014f393cc10e10bd',
					'svr'=>'app.cloopen.com',
					'tid'=>'53501',
				));
                break;
            case 'chefs.grain':
                //找厨网
                $module->setConfig(array(
                    'sid'=>'8a48b5514de7ae4c014decaf43e5027c',
                    'token'=>'84519f3ef1154c41b7df81074606842e',
                    'appid'=>'8a48b5515018a0f401504c138aa05de6',
                    'svr'=>'app.cloopen.com',
                    'tid'=>'41033',
                ));
                break;
            case 'yuecaibao.grain':
                //找厨网
                $module->setConfig(array(
                    'sid'=>'8a48b5514de7ae4c014decaf43e5027c',
                    'token'=>'84519f3ef1154c41b7df81074606842e',
                    'appid'=>'8a48b5515018a0f401504c138aa05de6',
                    'svr'=>'app.cloopen.com',
                    'tid'=>'41033',
                ));
                break;
            default:
        }		        
        $timeout = 5;
        if($is_verfify_code == false){
            $this->ajax(200,null);
        }
        if($this->jsonObj->mobile){
            $model = Controller::createMode($this->default_db,$this->getTableName('yanzhengma'));
            $yzm = $model->where(array('account'=>$this->jsonObj->mobile))->order('create_time desc')->limit(1)->select();
            if($yzm[0]['create_time']){
                $lastTime = strtotime($yzm[0]['create_time']);
            } else{
                $lastTime = 0;
            }
            if((time()-$lastTime) > $timeout*60){
                $current_verify_code = rand(123456,999999);
            } else {
                $current_verify_code = rand(123456,999999);
            }
            $result = $module->send($this->jsonObj->mobile,$current_verify_code,5);
            if($result->code == 0){
                Controller::createMode($this->default_db,$this->getTableName('yanzhengma'))->insert(
                    array('verify_code'=>$current_verify_code,'user_id'=>$this->jsonObj->user_id,'account'=>$this->jsonObj->mobile,'create_time'=>date('Y-m-d H:i:s')));
                $this->ajax(200,null);
            } else {
                $this->ajax(201,null);
            }
        }else{
            $this->ajax(400,null);
        }
    }

    //订单支付和充值
    public function payOrderAction(){
        //TODO 判断device_token
        $user_config = Controller::createMode($this->default_db,$this->getTableName('yonghupeizhi'))->getOne(array('user_id'=>$this->jsonObj->user_id));
        if(!empty($user_config['device_token']) && ($user_config['device_token'] != $this->jsonObj->device_token)){
            self::$_extensionArray['o']['charge'] = array();
            $this->ajax(209,'该账号在其他设备登录，请重新登录过后再尝试支付',self::$_extensionArray['o']);
        }
        $pingpp_module = $this->module('pingpp');
        $amount = $this->jsonObj->amount?$this->jsonObj->amount:0.1;

        //20170328
//        $orderid = $this->jsonObj->orderid?$this->jsonObj->orderid:1;
//        $order_id = $this->jsonObj->order_id?$this->jsonObj->order_id:1;
//        $orderid = $orderid<=1?$order_id:$orderid;
        $orderid = $this->jsonObj->order_id;
        if(!$orderid){

            $orderid = $this->jsonObj->orderid;
        }
        if(!$orderid){

            $this->ajax(211,'订单号不存在',self::$_extensionArray['o']);
        }

        $modelArray = array();
        //余额支付
        $money = $this->jsonObj->money?$this->jsonObj->money:0;

        $channel = $this->jsonObj->channel?$this->jsonObj->channel:'alipay';
        $pay_type = 2;
        $merchandise_name = '';
        if($orderid == -1){
            $orderid = $this->_getorderNo();
            //充值
            $pay_type = 1;
            $merchandise_name = '充值';
        }else if($orderid == -2){
            $orderid = $this->_getorderNo();
            //充机库币
            $pay_type = 3;
            $merchandise_name = '充币';
        }else{
            $model_order = Controller::createMode($this->default_db,'t_26_order_info');
            array_push($modelArray, $model_order);
            $order = $model_order->getOne(array('orderid'=>$orderid));
            if(!$order['orderid']){
                $this->ajax(211,'该订单不存在',self::$_extensionArray['o']);
            }
            $mlist = $model_order->from(array('p'=>$this->getTableName('order_product_list'), 'm'=>$this->getTableName('menu')),
                array('p.*,m.m_name,m.m_spec,m.m_tag,m.kind_id,m.m_usual_price'))->order("p.time desc")
                ->where("m.m_id = p.m_id and p.orderid = '".$order['orderid']."'")->select();
            if($this->jsonObj->api_key=='santianly.grain'){
                if((time()-$order['buytime'])>3600){
                    $this->ajax(210,'您的订单已过期，有效期为一小时。',self::$_extensionArray['o']);
                }
            }
        }
        if($mlist[0]['m_name']){
            $merchandise_name = csubstr($mlist[0]['m_name'],0,10);
        }

        //充值添加支付记录
        if($pay_type == 1 || $pay_type == 3){

            $recode = array(
                'orderid'=>$orderid,
                'balance'=>$money,
                'money'=>$amount,
                'channel'=>$channel,
                'amount'=>$amount+$money,
                'state'=>0,
            );

            //支付记录
            $modelPayRecode = Controller::createMode($this->default_db,$this->getTableName('zhifujilubiao'));
            array_push($modelArray, $modelPayRecode);

            $modelPayRecode->insert($recode);
        }

        switch($this->jsonObj->api_key){
            case 'guipiao.grain':
            case 'qianlong.grain':
                $pingxx_key = 'app_q18OOOW58CWT4OWD';
                $pingxx_secrect = 'sk_live_aLivXHH48yvPTSyfHOy1OKeL';
                $merchan_name = '[贵漂]'.$merchandise_name;
                break;
            case 'santianly.grain':
                //懋林公司
//                $pingxx_key = 'app_OaTSe5nrfvzPO84m';
//                $pingxx_secrect = 'sk_live_enLyv94Gm1i5y9CuzHv9qzjH';
                //三天公司
                $pingxx_key = 'app_Haf18CLiDyLOW9KG';
                $pingxx_secrect = 'sk_live_ivPGS8j5OqbDqPS0aHTynD4G';
                $merchan_name = '[中国天眼]'.$merchandise_name;
                break;
            case 'jiku999.grain':
                $pingxx_key = 'app_14i1S8m5qHW5Cybr';
                $pingxx_secrect = 'sk_live_zzDab1KC80q5izz1SKTiHu1G';
                $merchan_name = '[机库网]'.$merchandise_name;
                break;
            case 'junli.grain':
                $pingxx_key = 'app_T4y1ePOiXbH4fL0q';
                $pingxx_secrect = 'sk_live_e18OGOrXr10K8yv9eHOS8KO8';
                $merchan_name = '[汇厨网]'.$merchandise_name;
                break;
            case 'grain':
                $pingxx_key = 'app_0qzzDGufz5GCivHK';
                $pingxx_secrect = 'sk_live_iz5ybDz1iXHCHuTSqDjz5av9';
                $merchan_name = '[粮到了]'.$merchandise_name;
                break;
            case 'chefs.grain':
                //找厨网
                $pingxx_key = 'app_q18OOOW58CWT4OWD';
                $pingxx_secrect = 'sk_live_aLivXHH48yvPTSyfHOy1OKeL';
                $merchan_name = '[找厨网]'.$merchandise_name;
                break;
            default:
        }

        $pingpp_module->setConfig(array('channel'=>$channel,$amount,'app_id'=>$pingxx_key,'pingxx_api_key'=>$pingxx_secrect));
        //type 1充值，2下单
        self::$_extensionArray['o']['charge'] = json_decode($pingpp_module->pay($orderid,$amount*100,$merchan_name,
            json_encode(array("amount"=>$amount,"orderid"=>$orderid,"money"=>$money,"pay_type"=>$pay_type,"user_id"=>$this->jsonObj->user_id))));
        self::$_extensionArray['o']['orderid'] = $orderid;
        if(!self::$_extensionArray['o']['charge']){

            $this->__freeModel($modelArray);
            $this->ajax(211,'支付渠道出错',self::$_extensionArray['o']);
        }

        $this->__freeModel($modelArray);
        $this->ajax(200,'支付成功',self::$_extensionArray['o']);
    }

    //订单支付和充值
    public function paySelectAction(){
        $pingpp_module = $this->module('pingpp');
        $channel = $this->jsonObj->channel?$this->jsonObj->channel:'alipay';
        $pingxx_key = 'app_q18OOOW58CWT4OWD';
        $pingxx_secrect = 'sk_live_aLivXHH48yvPTSyfHOy1OKeL';
        $pingpp_module->setConfig(array('channel'=>$channel,1,'app_id'=>$pingxx_key,'pingxx_api_key'=>$pingxx_secrect));
        $res = $pingpp_module->select();
        var_dump($res);exit;
    }

    /**
     * 订单状态改变
     */
    public function orderStateAction(){
        $state = $this->jsonObj->handled;
        $data = $this->model->getOne("orderid='".$this->jsonObj->orderid."'");
        $data['handled'] = $state;
        $userId=$data['user_id'];
        if($userId!=$this->jsonObj->user_id){
            $this->ajax(201,'该订单不存在');
        }
        if(!in_array($state,array(2,3))){
            $this->ajax(203,'修改失败');
        }

        if( $this->model->updateData($data,array('orderid'=>$this->jsonObj->orderid)) ){
            $this->ajax(200,null);
        }else{
            $this->ajax(201,null);
        }
    }

    /**
     * 物流信息状态改变
     */
    public function orderDeliverStateAction(){
        $data = $this->model->getOne("orderid='".$this->jsonObj->orderid."'");
        $userId = $data['user_id'];
        if($userId!=$this->jsonObj->user_id){
            $this->ajax(201,'你没有权限操作该订单',array('update_time'=>date("Y-m-d H:i:s")));
        }
        if( $this->model->update(array('state'=>$this->jsonObj->state),array('orderid'=>$this->jsonObj->orderid)) ){
            //解析附件是否存在
            if($this->jsonObj->attach){
                $attach_model = Controller::createMode($this->default_db,$this->getTableName('dingdanpeisong_attach'));
                $attach_model->delete(array('sp_id'=>$data['id']));
                foreach($this->jsonObj->attach as $row){
                    $attach['sp_id'] = $data['id'];
                    $attach['file_name'] = $row->file_name;
                    $attach['file_type'] = $row->file_type?$row->file_type:0;
                    $attach_model->insert($attach);
                }
            }
            //更新订单状态
            $model_order_state_change = Controller::createMode($this->default_db,'t_26_order_state_change');
            if($model_order_state_change){
                $title = "";
                switch($this->jsonObj->state){
                    case 1:
                        $title .=  "亲，您的订单快递小哥已经开始处理了";
                        break;
                    case 2:
                        $title .=  "亲，您的订单快递小哥开始装车了";
                        break;
                    case 3:
                        $title .=  "亲，您的订单快递小哥装车完成了";
                        break;
                    case 4:
                        $title .=  "亲，您的订单快递小哥已经在途中了";
                        break;
                    case 5:
                        $title .=  "亲，您已经签收订单了";
                        break;
                }
                if($title){
                    $model_order_state_change->insert(array(
                        'orderid'=>$this->jsonObj->orderid,
                        'create_time'=>date("Y-m-d H:i:s"),
                        'state'=>0,
                        'title'=>$title,
                        'state_in'=>0,
                        'state_out'=>0,
                    ));
                }
            }
            $this->ajax(200,'ok',array('update_time'=>date("Y-m-d H:i:s")));
        }else{
            $this->ajax(201,'ok',array('update_time'=>date("Y-m-d H:i:s")));
        }
    }

    public function rePurchaseAction(){
        if($this->jsonObj){
            $data = array();
            $params = (array)$this->jsonObj;
            $mids = explode(',',$this->jsonObj->m_ids);
            foreach($mids as $m_id ){
                $params['m_id'] = $m_id;
                if(!$this->jsonObj->t_id){
                    //修改退货单
                    $data['last_insert_id'] = $this->model->addData($params);
                }else{
                    //创建退货单
                   $this->model->updateData($params,array('id'=>$this->jsonObj->t_id));
                    $data['last_insert_id'] = $this->jsonObj->t_id;
                }

            }
            if( $data['last_insert_id'] ){
                //解析附件是否存在
                $attach_model = Controller::createMode($this->default_db,$this->getTableName('tuihuoqingdan_attach'));
                $attach_model->delete(array('t_id'=>$data['last_insert_id']));
                foreach($params['attach'] as $row){
                    $attach['t_id'] = $data['last_insert_id'];
                    $attach['file_name'] = $row->file_name;
                    $attach['file_type'] = $row->file_type?$row->file_type:0;
                    $attach_model->insert($attach);
                }
                //修改订单状态为
                $orderModel = Controller::createMode($this->default_db,$this->getTableName('order_info'));
                $orderModel->update(array('handled'=>3),"orderid='".$this->jsonObj->orderid."'");
                $this->ajax(200,null,$data);
            }
            else{
                $data['last_insert_id'] = '';
                $this->ajax(417,null,$data);
            }
        }
    }

    /**
     * 支付确认
     */
    public function payConfirmAction(){
        //TODO 判断device_token
        $user_config = Controller::createMode($this->default_db,$this->getTableName('yonghupeizhi'))->getOne(array('user_id'=>$this->jsonObj->user_id));
        if(!empty($user_config['device_token']) && ($user_config['device_token'] != $this->jsonObj->device_token)){
            $this->ajax(209,null);
        }

        //余额
        $money = $this->jsonObj->money?$this->jsonObj->money:0;
        //金额
        $amount = $this->jsonObj->amount?$this->jsonObj->amount:0;
        $orderid = $this->jsonObj->order_id?$this->jsonObj->order_id:1;
        $channel = $this->jsonObj->channel?$this->jsonObj->channel:'alipay';
        $order_type = $this->jsonObj->order_type?$this->jsonObj->order_type:'1';//1充值，2订单,3机库币
        //已支付
        if($channel=='nopay'){
            $data['handled'] = 5;
        }else{
            $data['handled'] = 4;
        }

        $modelArray = array();
//        $data['price'] = $amount+$money;
        $modelOrder = Controller::createMode($this->default_db,$this->getTableName('order_info'));
        array_push($modelArray, $modelOrder);

        $orderidinfo = $modelOrder->getOne("orderid='".$orderid."'");

        //校验订单合法性
        if($order_type == 2 && !$orderidinfo['orderid']){

            $this->__freeModel($modelArray);//回收模型
            $this->ajax(211,'该订单不存在',self::$_extensionArray['o']);
        }

        $modelPayRecode = Controller::createMode($this->default_db,$this->getTableName('zhifujilubiao'));
        array_push($modelArray, $modelPayRecode);

        $recode = array(
            'orderid'=>$orderid,
            'balance'=>$money,
            'money'=>$amount,
            'channel'=>$channel,
            'amount'=>$amount+$money,
            'state'=>1,
        );
        //支付记录
        $modelPayRecode->update($recode,array('orderid'=>$orderid));
        if( $modelOrder->update($data,array('orderid'=>$orderid)) ){
            $model_jine = Controller::createMode($this->default_db,$this->getTableName('jinebiandongmingxibiao'));
            array_push($modelArray, $model_jine);

            $data = $model_jine->getOne("orderid='".$orderid."'");
            if($data['state'] == 1){
                //TODO 已经处理过的订单
            }else{
                if($order_type == 1){
                    //TODO 充值加金额
                    if($channel!='nopay') {
                        if($amount>0){
                            if ($model_jine->insert(array('type' => 1, 'amount' => $amount, 'remark' => '充值','state'=>1, 'orderid' => $orderid, 'user_id' => $this->jsonObj->user_id, 'create_time' => date("Y-m-d H:i:s")))) {
                                $user_model = Controller::createMode($this->default_db,$this->getTableName('yonghuliebiao'));
                                array_push($modelArray, $user_model);

                                $data = $user_model->getOne("user_id=" . $this->jsonObj->user_id);
                                $data['balance'] = $data['balance'] + $amount;
                                $user_model->update($data, "user_id=" . $this->jsonObj->user_id);
                            }
                        }
                    }
                }else if($order_type == 3){
                    //TODO 充值机库币
                    if($channel!='nopay' && $this->jsonObj->api_key=='jiku999.grain') {
                        if($amount>0){

                            //建立模型
                            $virtualCoin_model = Controller::createMode($this->default_db, 't_29_jikubibiandongmingxibiao');
                            array_push($modelArray, $virtualCoin_model);

                            $supplier_id = $this->jsonObj->supplier_id ? $this->jsonObj->supplier_id : 0;
                            //抵扣参数type|0=普通|1=专用，limit_supplier_id定向供应商编号
                            $coinParams = array(
                                'user_id'=>$this->jsonObj->user_id,
                                'amount'=>intval($amount * 100),
                                'remark'=>'机库币充值',
                                'type'=> $supplier_id > 0 ? 1 : 0,
                                'limit_supplier_id'=>$supplier_id,
                                'create_time'=>date("Y-m-d H:i:s")
                            );
                            $virtualCoin_model->insert($coinParams);
                            unset($coinParams);
                        }
                    }
                }
                if($order_type == 2){
                    //修改商品库存
                    $order_product_model = Controller::createMode($this->default_db,$this->getTableName('order_product_list'));
                    array_push($modelArray, $order_product_model);

                    $merchandise_model = Controller::createMode($this->default_db,$this->getTableName('menu'));
                    array_push($modelArray, $merchandise_model);

                    $order_product_list = $order_product_model->where("orderid = '".$orderid."'")->select();

                    //supplierId订单商品所属的供应商
                    $supplierIds = array();
                    foreach($order_product_list as $row ){
                        $merchandise_item = $merchandise_model->getOne("m_id={$row['m_id']}");

                        //获取供应商ID
                        if($merchandise_model){
                            array_push($supplierIds, $merchandise_item['m_supplier']);
                        }

                        $stock = $merchandise_item['m_stock']-$row['total'];
                        if($merchandise_item['m_stock']>0){
                            $merchandise_model->update(array('m_stock'=>$stock),array('m_id'=>$row['m_id']));
                        }
                        if($merchandise_item['m_tag'] == 1 && $stock < 1){
                            Controller::createMode('db_sys_26',$this->getTableName('menu'))->update(array('state'=>0),array('m_id'=>$row['m_id']));
                            continue;
                        }
                    }

                    /***发送消息 start wsl*****/
                    //去重supplierId
                    array_unique($supplierIds);
                    $supplierIdStr = implode(',', $supplierIds);
                    $userIds = Controller::createMode($this->default_db, $this->getTableName('supplier_relation'))->field('user_id')->where("m_supplier in (" . $supplierIdStr . ")")->group('user_id')->select();
                    //发送消息
                    if($userIds)
                        foreach($userIds as $row){
                            //msg_type:2
                            $this->_pushMessage(1, $row['user_id'],array('msg_type'=>2,'orderid'=>$orderid,'label'=>'您有新订单','title'=>'新订单提醒','content'=>'订单编号：'.$orderid), 0);
                        }
                    /***发送消息 end wsl*****/

                    //支付记录
                    if($money>0){
                        if($model_jine->insert(array('type'=>2,'amount'=>$money,'remark'=>'消费','state'=>1,'orderid'=>$orderid,'user_id'=>$this->jsonObj->user_id,'create_time'=>date("Y-m-d H:i:s")))){
                            //金额变动成功
                            $user_model = Controller::createMode($this->default_db,$this->getTableName('yonghuliebiao'));
                            array_push($modelArray, $user_model);

                            $data = $user_model->getOne("user_id=".$this->jsonObj->user_id);
                            $data['balance'] = $data['balance']-$money;
                            $user_model->update($data,"user_id=".$this->jsonObj->user_id);
                        }
                    }
                    //代金券被使用
                    $modelVoucher = Controller::createMode($this->default_db,$this->getTableName('yonghudaijinquanliebiao'));
                    array_push($modelArray, $modelVoucher);

                    $voucher_ids = explode(',',$orderidinfo['voucher_id']);
                    foreach($voucher_ids as $vid){
                        $modelVoucher->limit(1)->update(array('state'=>1),array('user_id'=>$this->jsonObj->user_id,'v_id'=>$vid,'state'=>0));
                    }
                    //配送券被使用
                    $modelVoucher->limit(1)->update(array('state'=>1),array('user_id'=>$this->jsonObj->user_id,'v_id'=>$orderidinfo['deliver_id']));
                }
            }

            //商品订单机库网支付成功计算推介人收益 开始
            if( $this->jsonObj->api_key=='jiku999.grain' && $orderid > 1 && $orderidinfo['type'] == 0){
                $user_model = Controller::createMode($this->default_db, $this->getTableName('yonghuliebiao'));
                array_push($modelArray, $user_model);

                $res = $user_model->getOne("user_id=".$this->jsonObj->user_id);//获取支付用户信息
                $re = $user_model->getOne("user_id=".$res['reference_id']);//获取推介人信息
                if( $re && $re['user_id'] > 1 ){//有推介人则计算收益

                    $tongyongpeizhi_model = Controller::createMode($this->default_db, $this->getTableName('tongyongpeizhibiao'));
                    array_push($modelArray, $tongyongpeizhi_model);

                    $result = $tongyongpeizhi_model->getOne("id=84");
                    $tongyongpeizhi_model->close();
                    $config_info = json_decode($result['config_value']);
                    $point = $config_info->proceeds_point;
                    $proceeds = round($re['proceeds'],2);
                    $proceeds = $proceeds+($amount+$money)*$point/100;
                    $proceeds = round($proceeds,2);
                    $sql = 'update ' . $this->getTableName('yonghuliebiao') . ' set proceeds=' . $proceeds . ' where user_id=' . $re['user_id'];
                    $user_model->execute($sql);
                    $proceeds_arr = array('user_id'=>$re['user_id'],
                        'customer_id'=>$this->jsonObj->user_id,
                        'orderid'=>$orderid,
                        'total'=>$amount,
                        'proceeds'=>($amount+$money)*$point/100,
                        'remark'=>'订单'.$orderid.'收益',
                        'type'=>1);
                    $shouyi_model = Controller::createMode($this->default_db, 't_29_shouyibiao');
                    array_push($modelArray, $shouyi_model);
                    $shouyi_model->insert($proceeds_arr);
                }
                //机库网支付成功计算推介人收益 结束

                /***消费赠送机库币 start***/
                if($amount > 0){

                    //建立模型
                    $virtualCoin_model = Controller::createMode($this->default_db, 't_29_jikubibiandongmingxibiao');
                    array_push($modelArray, $virtualCoin_model);

                    //抵扣参数type|0=普通|1=专用，limit_supplier_id定向供应商编号
                    $coinParams = array(
                        'user_id'=>$this->jsonObj->user_id,
                        'amount'=>intval($amount),
                        'remark'=>'订单'.$orderid.'消费赠送',
                        'type'=>0,
                        'limit_supplier_id'=>0,
                        'create_time'=>date("Y-m-d H:i:s")
                    );
                    $virtualCoin_model->insert($coinParams);
                    unset($coinParams);
                }
                /***消费赠送机库币 end***/
            } else if( $this->jsonObj->api_key=='jiku999.grain' && $orderidinfo['type'] == 1){
                //维修单订单状态变更为“4=已支付待维修”

                $repairOrderUpdateModel = Controller::createMode($this->default_db, 't_29_repair_order');
                array_push($modelArray, $repairOrderUpdateModel);

                $order_product_model = Controller::createMode($this->default_db,$this->getTableName('order_product_list'));
                array_push($modelArray, $order_product_model);

                $orderProduct = $order_product_model->getOne("orderid = '".$orderidinfo['orderid']."'");
                $orderMap['id'] = $orderProduct['m_id'];
                $orderMap['user_id'] = $orderidinfo['user_id'];

                $orderUpdateData['handled'] = 4;
                $updateResult = $repairOrderUpdateModel->update($orderUpdateData, $orderMap);

                if($updateResult){
                    //推送消息
                    $xiaoxi_model = Controller::createMode($this->default_db, 't_29_server_xiaoxi');
                    array_push($modelArray, $xiaoxi_model);

                    $xiaoxiData = array();
                    $xiaoxiData['from_id'] = '10000';
                    $xiaoxiData['msg_content'] = '维修单号'.$orderProduct['m_id'].'已支付，请尽快维修。';
                    $xiaoxiData['to_id'] = $orderProduct['s_id'];
                    $xiaoxiData['type'] = 1;
                    $xiaoxiData['create_time'] = date("Y-m-d H:i:s");
                    $xiaoxi_model->insert($xiaoxiData);

                    $xiaoxiData['title'] = '维修单号'.$orderProduct['m_id'].'有最新动态';
                    $xiaoxiData['msg_type'] = 4;
                    $xiaoxiData['orderid'] = $orderProduct['m_id'];
                    $this->_pushMessage(1, $xiaoxiData['to_id'], $xiaoxiData, 0);
                }

                unset($orderUpdateData);
                unset($orderMap);
            }


            if($this->jsonObj->api_key=='santianly.grain' && ($this->jsonObj->channel == 'alipay' || $this->jsonObj->channel == 'wx') ){
                //TODO 订单支付状态校验
                //平塘票务处理
                $this->module('otaclient');
                $ota = Otaclient::orderFinish('S20160914',$orderid);
                if($ota->ResultCode == '00'){
                    $obj = json_decode($ota->ResultJson);
                    $ecode = $obj[0]->ECode;
                    $ecode_url = $obj[0]->UrlECode;
                    $model = Controller::createMode($this->default_db,'t_30_ota_ecode_recode');
                    array_push($modelArray, $model);

                    if($model->getOne(array('orderid'=>$orderid))){
                        $model->replace(array('ecode'=>$ecode,'orderid'=>$orderid,'is_notice'=>1,'ecode_url'=>$ecode_url),array('orderid'=>$orderid));
                    }else{
                        $model->replace(array('ecode'=>$ecode,'orderid'=>$orderid,'is_notice'=>0,'ecode_url'=>$ecode_url),array('orderid'=>$orderid));
                    }
                }
            }

            $this->__freeModel($modelArray);//回收模型
            $this->ajax(200,null);
        }else{

            $this->__freeModel($modelArray);//回收模型
            $this->ajax(201,null);
        }
    }

    public function myInfoAction(){
        $modelArray = array();
		$this->model = Controller::createMode('db_sys_26_71',$this->getTableName('yonghuliebiao'));
        $orders = $this->model->from($this->getTableName('order_info'))->where('user_id='.$this->jsonObj->user_id." and handled>0")->select();
        self::$_extensionArray['o']['orders_num'] = count($orders);
        $total_price = 0;
        $total_orginal = 0;
        $merchandis = array();
        foreach($orders as $ord){
            $order_product_list = $this->model->from($this->getTableName('order_product_list'),'m_id')->where("orderid = '".$ord['orderid']."'")->select();
            foreach($order_product_list as $p){

                if($merchandis[$p['m_id']]){
                    $mmid = $merchandis[$p['m_id']];
                }else{
                    $mmid = $this->model->from($this->getTableName('menu'),array('m_usual_price','m_price'))->where(array('m_id'=>$p['m_id']))->select(false);
                    $merchandis[$p['m_id']] = $mmid;
                }
                $total_orginal += $p['total'] * $mmid['m_usual_price'];
                $total_price += $p['total'] * $mmid['m_price'];
                unset($mmid);
            }
        }

        //

        //省了多少
        self::$_extensionArray['o']['omit_money'] = round(abs($total_orginal-$total_price),2);

        //余额
        $yonghu_Model = Controller::createMode($this->default_db,$this->getTableName('yonghuliebiao'));
        array_push($modelArray, $yonghu_Model);

        $info = $yonghu_Model->getOne("user_id='".$this->jsonObj->user_id."'");
        if($this->jsonObj->api_key=='jiku999.grain'){
            self::$_extensionArray['o']['balance'] = round(($info['balance']+$info['proceeds']),2);
        }else{
            self::$_extensionArray['o']['balance'] = round($info['balance'],2);
        }
        //该用户是否是供应商
        $supplier_model = Controller::createMode($this->default_db,$this->getTableName('supplier_relation'));
        array_push($modelArray, $supplier_model);

        $supplier = $supplier_model->getOne(array('user_id'=>$this->jsonObj->user_id));
        if($supplier['m_supplier']){
            self::$_extensionArray['o']['supplier_id'] = $supplier['m_supplier'];
        }else{
            self::$_extensionArray['o']['supplier_id'] = 0;
        }

   
        self::$_extensionArray['o']['info'] = $info?$info:array('user_id'=>0,'user_name'=>'');
        //券包数量
        $yonghudaijinquan_model = Controller::createMode($this->default_db, $this->getTableName('yonghudaijinquanliebiao'));
        array_push($modelArray, $yonghudaijinquan_model);
        $user_voucher_list = $yonghudaijinquan_model->where(array('user_id'=>$this->jsonObj->user_id,'state'=>0))->select();
        if($user_voucher_list && count($user_voucher_list) > 0){
            $vids = array();
            foreach($user_voucher_list as $uv){
                $vids[] = $uv['v_id'];
            }
            $daijinnquan_model = Controller::createMode($this->default_db,$this->getTableName('daijinquan'));
            array_push($modelArray, $daijinnquan_model);
            foreach($vids as $vid){
                $m = array();
                $m['voucher_id'] = $vid;
                $voucher_list[] = $daijinnquan_model->getOne($m);
            }
            $vlist = array();
            foreach($voucher_list as $row ){
                //过期限制
                $current_time = date("Y-m-d H:i:s");
                if($current_time < $row['begin_time'] || $current_time > $row['end_time'] ) {
                    continue;
                }
                //金额限制
                if(isset($this->jsonObj->amount) && $this->jsonObj->amount >= 0){
                    if($row['limit_money']>0 && $this->jsonObj->amount < $row['limit_money']) {
                        continue;
                    }
                }
                //是否使用
                if($row['state']>0) {
                    continue;
                }
                $vlist[] = $row;
            }
        }
        self::$_extensionArray['o']['vouchers_num'] = $vlist ? count($vlist) : 0;

        if($this->jsonObj->api_key=='jiku999.grain'){

            self::$_extensionArray['o']['order_handled_count']   = array(
                array('handled'=>0,'count'=>$this->model->count($this->getTableName('order_info'),'1',array('user_id'=>$this->jsonObj->user_id,'handled'=>0, 'type'=>0))),
                array('handled'=>1,'count'=>$this->model->count($this->getTableName('order_info'),'1',array('user_id'=>$this->jsonObj->user_id,'handled'=>1, 'type'=>0))),
                array('handled'=>2,'count'=>$this->model->count($this->getTableName('order_info'),'1',array('user_id'=>$this->jsonObj->user_id,'handled'=>2, 'type'=>0))),
                array('handled'=>3,'count'=>abs($this->model->count($this->getTableName('order_info'),'1',array('user_id'=>$this->jsonObj->user_id,'handled'=>3, 'type'=>0))
                    -$this->model->count($this->getTableName('tuihuoqingdan'),'1',array('user_id'=>$this->jsonObj->user_id,'state'=>1)))),
                array('handled'=>4,'count'=>$this->model->count($this->getTableName('order_info'),'1',array('user_id'=>$this->jsonObj->user_id,'handled'=>4, 'type'=>0))),
                array('handled'=>5,'count'=>$this->model->count($this->getTableName('order_info'),'1',array('user_id'=>$this->jsonObj->user_id,'handled'=>5, 'type'=>0))),
            );
        } else {

            self::$_extensionArray['o']['order_handled_count']   = array(
                array('handled'=>0,'count'=>$this->model->count($this->getTableName('order_info'),'1',array('user_id'=>$this->jsonObj->user_id,'handled'=>0))),
                array('handled'=>1,'count'=>$this->model->count($this->getTableName('order_info'),'1',array('user_id'=>$this->jsonObj->user_id,'handled'=>1))),
                array('handled'=>2,'count'=>$this->model->count($this->getTableName('order_info'),'1',array('user_id'=>$this->jsonObj->user_id,'handled'=>2))),
                array('handled'=>3,'count'=>abs($this->model->count($this->getTableName('order_info'),'1',array('user_id'=>$this->jsonObj->user_id,'handled'=>3))
                    -$this->model->count($this->getTableName('tuihuoqingdan'),'1',array('user_id'=>$this->jsonObj->user_id,'state'=>1)))),
                array('handled'=>4,'count'=>$this->model->count($this->getTableName('order_info'),'1',array('user_id'=>$this->jsonObj->user_id,'handled'=>4))),
                array('handled'=>5,'count'=>$this->model->count($this->getTableName('order_info'),'1',array('user_id'=>$this->jsonObj->user_id,'handled'=>5))),
            );
        }

        $this->__freeModel($modelArray);//回收模型

        $this->ajax(200,'ok',self::$_extensionArray['o']);
    }


    /***
     * 收益转出到余额接口
     */
    public function transOutProceedsAction(){

        $modelArray = array();

        //余额
        $model_balance_model = Controller::createMode($this->default_db,$this->getTableName('yonghuliebiao'));
        array_push($modelArray, $model_balance_model);
        $model_config_settings = Controller::createMode($this->default_db,$this->getTableName('tongyongpeizhibiao'));
        array_push($modelArray, $model_config_settings);
        $model_jine = Controller::createMode($this->default_db,$this->getTableName('jinebiandongmingxibiao'));
        array_push($modelArray, $model_jine);

        $info = $model_balance_model->getOne("user_id=".$this->jsonObj->user_id);

        $transOutingMoney = $this->jsonObj->amount;

        $transOutLimitAmount = 50;
        $configInfo = $model_config_settings->getOne("id=87");
        $transOutConfig = json_decode($configInfo['config_value']);
        if($transOutConfig && $transOutConfig->trans_out_limit){

            $transOutLimitAmount = $transOutConfig->trans_out_limit;
        }

        if(!$info){

            $this->__freeModel($modelArray);
            $this->ajax(204, '转出信息有误。');
        }else if(!$transOutingMoney){

            $this->__freeModel($modelArray);
            $this->ajax(201, '请输入转出金额。');
        }else if($info['proceeds'] < $transOutingMoney){

            $this->__freeModel($modelArray);
            $this->ajax(202, '您的收益不足。');
        }else if($transOutingMoney < $transOutLimitAmount){

            $this->__freeModel($modelArray);
            $this->ajax(203, '转出金额不能小于'.$transOutLimitAmount.'。');
        }

        $result = $model_balance_model->update(array(

            'balance'=> round(($info['balance'] + $transOutingMoney), 2),
            'proceeds'=> round(($info['proceeds'] - $transOutingMoney), 2)
        ), "user_id=".$this->jsonObj->user_id);

        $moneychangeParam = array('type' => 1, 'amount' => $transOutingMoney, 'remark' => '收益转出', 'state' => 1, 'orderid' => '-1', 'user_id' => $this->jsonObj->user_id, 'create_time' => date("Y-m-d H:i:s"));
        if($result){//成功

            $moneychangeParam['state'] = 1;
            $model_jine->insert($moneychangeParam);
            unset($moneychangeParam);

            //收益表转出流水记录
            $proceeds_arr = array('user_id'=>$this->jsonObj->user_id,
                'customer_id'=>$this->jsonObj->user_id,
                'total'=>0,
                'proceeds'=>$transOutingMoney,
                'remark'=>'收益转出到余额',
                'type'=>2);
            $shouyi_model = Controller::createMode($this->default_db, 't_29_shouyibiao');
            array_push($modelArray, $shouyi_model);
            $shouyi_model->insert($proceeds_arr);

            $this->__freeModel($modelArray);
            $this->ajax(200,'转出操作成功！');
        } else {//失败

            $moneychangeParam['state'] = 0;
            $model_jine->insert($moneychangeParam);
            unset($moneychangeParam);
            $this->__freeModel($modelArray);
            $this->ajax(205,'转出操作失败！');
        }
    }

    /**
     * 供应商确认单
     */
    public function supplierOrderConfirmAction(){
        if($this->jsonObj->id && $this->jsonObj->total){
            $order_product_model = Controller::createMode($this->default_db,$this->getTableName('order_product_list'));
            $item = $order_product_model->getOne(array('id'=>$this->jsonObj->id));
            $order = Controller::createMode($this->default_db,$this->getTableName('order_info'))->getOne(array('orderid'=>$item['orderid']));
            if($item){
                $mitem = Controller::createMode($this->default_db,$this->getTableName('menu'))->getOne(array('m_id'=>$item['m_id']));
                $sitem =  Controller::createMode($this->default_db,$this->getTableName('supplier_relation'))->getOne(array('m_supplier'=>$mitem['m_supplier']));
                if($sitem['user_id'] != $this->jsonObj->user_id){
                    $this->ajax(203,'error');
                }else{
                    if($this->jsonObj->total){
                        $supplier_user = Controller::createMode($this->default_db,$this->getTableName('supplier_relation'))
                            ->field('m_supplier')->getOne(array('user_id'=>$this->jsonObj->user_id));
                        //先判断是否缺货状态
                        if($this->jsonObj->total > 0){
                            $total = ($mitem['m_spec'] == 0 ?($this->jsonObj->total / 500) : $this->jsonObj->total);
                        }else{
                            $total = $this->jsonObj->total;
                        }
                        $stock_confirm = array(
                            'id'=>$this->jsonObj->id,
                            's_id'=>$supplier_user['m_supplier'],
                            'user_id'=>$item['user_id'],
                            'price'=>$item['price'],
                            's_price'=>$mitem['m_min_price'],
                            'deliver_time'=>$order['deliver_time'],
                            'confirm_id'=>$this->jsonObj->user_id,
                            'remark'=>$item['remark'],
                            'total'=>$total,//换算成斤后存储
                            'orderid'=>$item['orderid'],
                            'm_id'=>$item['m_id'],
                        );
                        if(!empty($this->jsonObj->seller_remark)){
                            $stock_confirm['seller_remark'] = $this->jsonObj->seller_remark;
                        }
                        $stock_confirm_model = Controller::createMode($this->default_db,$this->getTableName('order_stock_confirm'));
                        if($stock_confirm_model->getOne(array('orderid'=>$item['orderid'],'m_id'=>$item['m_id']))){
                            $this->ajax(204,'只能修改一次,如果还需要修改请联系军立客服人员');
                        }else{
                            $stock_confirm_model->insert($stock_confirm);
                        }
                    }
                }
                //正负百分之十
                if($this->jsonObj->total > 0){
                    if($mitem['m_spec'] == 0){

                        $update_attr['total'] = ($this->jsonObj->total / 500);//换算成斤后存储
                    } else {

                        $update_attr['total'] =  $this->jsonObj->total;
                    }
                }
                if(!empty($this->jsonObj->seller_remark)){
                    $update_attr['seller_remark'] = $this->jsonObj->seller_remark;
                }
                if(count($update_attr) == 0 || $order_product_model->update($update_attr,array('id'=>$this->jsonObj->id))){
                    $this->ajax(200,'ok');
                }else{
                    $this->ajax(201,'error');
                }
            }else{
                $this->ajax(202,'error');
            }
        } else if($this->jsonObj->user_id && $this->jsonObj->deliver_time){

            $deliver_time = $this->jsonObj->deliver_time;
            if(strpos($deliver_time,'-')){
                $deliver_time = strtotime($deliver_time);
            }

            $now_date = date('Y-m-d');
            $now_date = strtotime($now_date);
            if($deliver_time < $now_date){

                $this->ajax(205,'error');
            }

            $deliver_time = date("Y-m-d",$deliver_time);
            //供应商信息
            $sitem =  Controller::createMode($this->default_db,$this->getTableName('supplier_relation'))->getOne(array('user_id'=>$this->jsonObj->user_id));
            if(!$sitem['m_supplier']){
                $this->ajax(206,'error');
            }
            if($sitem){
                $m_supplier = $sitem['m_supplier'];
                $alertWhere = "orderProduct.s_id = $m_supplier
                            and orderInfo.orderid = orderProduct.orderid
                            and orderInfo.deliver_time like '".$deliver_time."%' and orderInfo.handled in (4,5)";
                if($this->jsonObj->m_id){//具体的某一样菜
                    $mId = $this->jsonObj->m_id;
                    $alertWhere .= " and orderProduct.m_id=$mId";
                }
                $tableOrderProductName = $this->getTableName('order_product_list');
                //根据条件配送日期、供应商ID查询订单信息集合
                $order_product_list = Controller::createMode($this->default_db, $tableOrderProductName)
                        ->from(array(
                            'orderInfo'=>$this->getTableName('order_info'),
                            'orderProduct'=>$tableOrderProductName
                        ), array('orderProduct.id, orderProduct.m_id,orderProduct.user_id,orderProduct.price, orderProduct.orderid,
                              orderProduct.total,orderProduct.truetotal,orderInfo.deliver_time'))
                        ->where($alertWhere)//未发货订单
                        ->order("orderProduct.orderid desc")
                        ->select();
                if($order_product_list){
                    $seller_remark = $this->jsonObj->seller_remark;
                    $stock_confirm_model = Controller::createMode($this->default_db, $this->getTableName('order_stock_confirm'));

                    $count = 0;
                    $supplier_user = Controller::createMode($this->default_db,$this->getTableName('supplier_relation'))
                        ->field('m_supplier')->getOne(array('user_id'=>$this->jsonObj->user_id));
                    $merchandise_model = Controller::createMode($this->default_db,$this->getTableName('menu'));
                    foreach($order_product_list as $row ){
                        $mitem = $merchandise_model->getOne(array('m_id'=>$row['m_id']));
                        $stock_confirm = array(
                            'id'=>$row['id'],
                            's_id'=>$supplier_user['m_supplier'],
                            'total'=>$row['total'],
                            'user_id'=>$row['user_id'],
                            'remark'=>$row['remark'],
                            'price'=>$row['price'],
                            'confirm_id'=>$this->jsonObj->user_id,
                            's_price'=>$mitem['m_min_price'],
                            'deliver_time'=>$row['deliver_time'],
                            'orderid'=>$row['orderid'],
                            'm_id'=>$row['m_id'],
                        );
                        if(!empty($seller_remark)){
                            $stock_confirm['seller_remark'] = $seller_remark;
                        }

                        //order_stock_confirm表中没有对应记录的插入相应条数
                        if($stock_confirm_model->getOne(array('orderid'=>$row['orderid'], 'm_id'=>$row['m_id']))){
                        }else{

                            $result = $stock_confirm_model->insert($stock_confirm);
                            if(!$result)
                                ++$count;
                        }
                    }

                    if($count == 0){

                        $this->ajax(200,'ok');
                    }else{

                        $this->ajax(201,'error');
                    }
                } else {

                    $this->ajax(200,'ok');
                }

                } else {

                    $this->ajax(203,'unauthorized access');
                }
        }
        $this->ajax(205,'error');
    }


    /**
     * 供应商日报
     */
    public function supplierDialyAction(){
        $stat_dt = $this->jsonObj->stat_dt;//配送日期
        $handled = $this->jsonObj->handled;
        if($stat_dt && strpos($stat_dt,'-')){
            $stat_dt = strtotime($stat_dt);
        }
        if($stat_dt)
            $stat_dt = date("Y-m-d",$stat_dt);
        self::$_extensionArray['o']['stat_dt'] = strtotime($stat_dt);
        $supplier_relation = $this->model->from($this->getTableName('supplier_relation'))->where(array('user_id'=>$this->jsonObj->user_id))->select(false);
        if(!$supplier_relation){
            $this->ajax(201,'unauthorized access');
        }
        $m_supplier = $supplier_relation['m_supplier'];
        $merchandises = Controller::createMode($this->default_db,$this->getTableName('menu'))
            ->where(array('m_supplier'=>$m_supplier))
            ->group('m_id')
            ->select();
        $str = '';
        $spec_ids = array();
        foreach($merchandises as $product){
            $str .= $product['m_id'].',';
            if(!in_array($product['m_spec'],$spec_ids)){
                $spec_ids[] = $product['m_spec'];
            }
        }
        $str = substr($str,0,-1);
        $where = "orderProduct.m_id in (".$str.") and orderInfo.handled in ($handled)";
        if($stat_dt){//有配送日期则过滤
            $where .= " and orderInfo.deliver_time like '".$stat_dt."%'";
        }
        $order_product_list = $this->model
            ->from(array(
                'orderProduct'=>$this->getTableName('order_product_list')
            ), array('orderProduct.id, orderProduct.m_id, orderProduct.user_id, orderProduct.orderid, orderProduct.total, orderProduct.price,
                    orderProduct.truetotal, orderProduct.trueprice, orderProduct.remark, orderProduct.seller_remark, orderProduct.time', 'orderInfo.deliver_time, orderInfo.handled'))
            ->join(array(
                'orderInfo'=>$this->getTableName('order_info')
            ), 'orderInfo.orderid = orderProduct.orderid')
            ->where($where)
            ->order("orderProduct.orderid desc")
            ->select();
        $user_ids = array();
        $orderids = array();
        foreach($order_product_list as $key=>$row ){
            if(!in_array($row['user_id'],$user_ids)){
                $user_ids[] = $row['user_id'];
            }
            if(!in_array($row['orderid'],$orderids)){
                $orderids[] = $row['orderid'];
            }
        }
        $attachs = $this->model->from($this->getTableName('attach'))->group('m_id')->where("m_id in (".$str.")")->select();
        $userids = $this->model->from($this->getTableName('yonghuliebiao'))->where("user_id in (".implode(',',$user_ids).")")->select();
        $orders = $this->model->from($this->getTableName('order_info'))->where("orderid in (".implode(',',$orderids).")")->select();
        $spec_names = $this->model->from($this->getTableName('spec_info'))->where("spec_id in (".implode(',',$spec_ids).")")->select();
        $orders_confirms = $this->model->from($this->getTableName('order_stock_confirm'))->where("orderid in (".implode(',',$orderids).") and m_id in (".$str.") ")->select();
        foreach($order_product_list as $key=>$row ){
            foreach($merchandises as $product){
                if($product['m_id'] == $row['m_id']){
                    $m = $product;
                }
            }
            $tagName = $m['tag_name'];
            //斤转换成克
            if($m['m_spec'] == 0){
                $order_product_list[$key]['total'] = 500*$order_product_list[$key]['total'];
            }
            $order_product_list[$key]['m_name'] = $m['m_name'];
            //进货价
            $order_product_list[$key]['m_min_price'] = $m['m_min_price'];
            $order_product_list[$key]['m_id'] = $row['m_id'];
            $order_product_list[$key]['id'] = $row['id'];
            $order_product_list[$key]['time'] = date("Y-m-d H:i:s",$row['time']);
            $order_product_list[$key]['m_price'] = $row['price'];
            $order_product_list[$key]['kind_id'] = $m['kind_id'];
            foreach($spec_names as $spec){
                if($spec['spec_id'] == $m['m_spec']){
                    $order_product_list[$key]['m_spec_name'] = ($tagName ? "{$tagName}/{$spec['spec_name']}":$spec['spec_name']);
                }
            }
            $order_product_list[$key]['remark'] = $row['remark'];
            $order_product_list[$key]['seller_remark'] = $row['seller_remark'];
            $order_product_list[$key]['truetotal'] = $row['truetotal']?$row['truetotal']:$row['total'];
            $order_product_list[$key]['trueprice'] = $row['trueprice']?$row['trueprice']:$row['price'];
            foreach($userids as $user){
                if($user['user_id'] == $row['user_id']){
                    $order_product_list[$key]['user_name'] = $user['user_name'];
                    $order_product_list[$key]['mobile'] = $user['mobile'];
                }
            }
            foreach($attachs as $attach){
                if($attach['m_id'] == $row['m_id']){
                    $order_product_list[$key]['filename'] = $attach['file_name'];
                }
            }
            foreach($orders_confirms as $confirm){
                if($confirm['orderid'] == $row['orderid'] && $confirm['m_id'] == $row['m_id']){
                    $confirm = $confirm;
                }
            }
            $order_product_list[$key]['out_of_stock'] = 0;
            if($confirm){
                $order_product_list[$key]['is_confirm'] = 1;
                if($confirm['total'] < 0){//小于0的就表示缺货
                    //缺货
                    $order_product_list[$key]['out_of_stock'] = 1;
                }
            }else{
                $order_product_list[$key]['is_confirm'] = 0;
            }
            foreach($orders as $order){
                if($order['orderid'] == $row['orderid']){
                    $order_product_list[$key]['handled_name'] = getFieldNameByFieldComment($order['handled'],$this->default_db,$this->getTableName('order_info'),'handled');
                }
            }
        }
		self::$_extensionArray['o']['list'] = array();
		if($this->jsonObj->is_group == 1){
			$first_result = array();
			foreach($order_product_list as $key => $row){
				$first_result[$row['m_id']][] = $row;
			}
			foreach($first_result as $row ){
				$arr = array('name'=>$row[0]['m_name'],'detail'=>$row);
				self::$_extensionArray['o']['list'][] = $arr;
			}
		}else{
			 self::$_extensionArray['o']['list'] = $order_product_list;
		}       
        $this->ajax(200,'ok',self::$_extensionArray['o']);
        exit;
    }

    /**
     * 文章列表
     */
    public function articleAction(){
        //type 1 通用配置
        if($this->jsonObj->type = 2 && $this->jsonObj->id){
            $info = Controller::createMode($this->default_db,$this->getTableName('tongyongpeizhibiao'))->find($this->jsonObj->id);
            echo $info['remark'];exit;
        }
    }

    public function pushAction(){
        $model = Controller::createMode($this->default_db,$this->getTableName('xitongxiaoxi'));
        $model_user = Controller::createMode($this->default_db,$this->getTableName('yonghupeizhi'));
        $msglist = $model->where(array('state'=>0))->select();
        foreach($msglist as $row ){
            $uids = array();
            if($row['limit_area']==0){
                $us = $model_user->select();
                foreach($us as $u){
                    if(!in_array($u['user_id'],$uids)){
                        $uids[] = $u['user_id'];
                    }
                }
            }
            if($row['limit_area']>0){
                $us = $model_user->where(array('client_type'=>$row['limit_area']))->select();
                foreach($us as $u){
                    if(!in_array($u['user_id'],$uids)) {
                        $uids[] = $u['user_id'];
                    }
                }
            }
            if($row['limit_uids']){
                $uids = explode(',',$row['limit_uids']);
            }
            foreach($uids as $u){
                $content_obj = json_decode($row['msg_content']);
                //订单状态提醒
                if($content_obj->msg_type == 1){
                    $title = $content_obj->title;
                }
                $res = $this->_pushMessage(1,$u,array('fromUserId'=>0,'toUserId'=>$u,'label'=>$row['msg_title'],'title'=>$title?$title:$row['msg_title'],'content'=>$row['msg_content']),$row['type']);
            }
            if($res['result'] == 'ok'){
                $model->update(array('state'=>1),array('id'=>$row['id']));
            }
        }
        if($res['result'] == 'ok'){
            $this->ajax(200,$res['result']);
        }else{
            $this->ajax(400,$res['result']);
        }
    }

    public function cronAction(){
        $model = Controller::createMode($this->default_db,$this->getTableName('menu'));
        $list = $model->select();
        foreach($list as $key=>$row ){
            $valid_time = strtotime($row['m_deliver_limit_time']);
            if($row['m_tag'] == 1 && ($row['m_stock'] < 1 || time() > $valid_time)){
                $this->model->update(array('state'=>0),array('m_id'=>$row['m_id']));
                continue;
            }
        }
        $this->ajax(200,null);
    }

    /**
     * 随机获取一个代金卷
     */
    public function shareVoucherAction(){
        //TODO 判断活动是否有效
        $model_redrain_activity = Controller::createMode($this->default_db,'t_26_redrain_activitys');
        $activity = $model_redrain_activity->getOne(array('id'=>$this->jsonObj->aid));
        $time = strtotime($activity['start_time']) - time();
        $time_over = strtotime($activity['end_time']) - time();
        if($time>0){
            $this->ajax(201,'很遗憾，活动还未开始，请耐心等待.');
        }
        if($time_over < 0 || $activity['state'] == 0){
            $this->ajax(202,'很遗憾，本次活动已结束,期待您下次再来.');
        }
        $model = Controller::createMode($this->default_db,'t_26_voucher_issued');
        $model_supplier = Controller::createMode($this->default_db,'t_26_suppliers');
        $arr = $model->execute("select * from t_26_voucher_issued where aid={$this->jsonObj->aid} and state = 0 and user_id = 0 order by rand() limit 200");
        if(count($arr) == 0){
            $this->ajax(205,'很遗憾，本次活动的红包已经被抢光了,期待您下次参与.');
        }
        $item_id = array_rand($arr);
        self::$_extensionArray['o'][0] = $arr[$item_id];
        $v_id = self::$_extensionArray['o'][0]['v_id'];
        $model_voucher = Controller::createMode($this->default_db,'t_26_daijinquan');
        $voucher = $model_voucher->getOne(array('voucher_id'=>$v_id));
        $result = array();
        if($voucher){
            if($voucher['limit_supplier_id']){
                $supplier = $model_supplier->getOne(array('s_id'=>$voucher['limit_supplier_id']));
                $result['title'] = '恭喜您，获得1张'.$supplier['s_name'].'专用代金卷.';
            }else{
                $result['title'] = '恭喜您，获得1张机库网通用的代金卷.';
            }
            $result['worth'] = $voucher['worth'];
            $result['issue_id'] = self::$_extensionArray['o'][0]['id'];
        }
        $this->ajax(200,'ok',$result);
    }


    /**
     * 领取代金卷
     */
    public function getVouchersAction(){
        $model = Controller::createMode($this->default_db,'t_26_voucher_issued');
        $model_user = Controller::createMode($this->default_db,'t_26_yonghuliebiao');
        $model_user_daijinquan = Controller::createMode($this->default_db,'t_26_yonghudaijinquanliebiao');
        $model_redrain_activity = Controller::createMode($this->default_db,'t_26_redrain_activitys');
        //获取用户的user_id
        $current_user = $model_user->getOne(array('mobile'=>$this->jsonObj->mobile));
        if(!$current_user){
            //该用户暂未注册
            $this->ajax(201,'请你先注册成为机库网的用户后再领取.');
        }else {
            //TODO 判断活动是否有效
            $activity = $model_redrain_activity->getOne(array('id'=>$this->jsonObj->aid));
            $time = strtotime($activity['start_time']) - time();
            $time_over = strtotime($activity['end_time']) - time();
            if($time>0){
                $this->ajax(207,'很遗憾，活动还未开始，请耐心等待.');
            }
            if($time_over < 0 || $activity['state'] == 0){
                $this->ajax(206,'很遗憾，本次活动已结束,,期待您下次参与.');
            }
            //TODO 判断该用户已有代金卷数量
            $user_issued_total = $model->where(array('user_id'=>$current_user['user_id'],'aid'=>$this->jsonObj->aid,'state'=>1))->count("t_26_voucher_issued",'1');
            $activity_issued_total = $model->where(array('aid'=>$this->jsonObj->aid,'state'=>1))->count("t_26_voucher_issued",'1');
            if($activity_issued_total >= $activity['limit_total']){
                $this->ajax(205,'很遗憾，本次活动的红包已经被抢光了,期待您下次参与.');
            }
            if($user_issued_total >= $activity['personal_total']){
                $this->ajax(204,'您已经拥有'.$user_issued_total.'张本次活动的代金卷了,期待您下次参与.');
            }
            if(!$this->jsonObj->ids){
                $this->ajax(202,'您没有选择代金卷.');
            }else{
                $ids = explode(',',$this->jsonObj->ids);
                if(count($ids)>0){
                    //写入用户代金卷列表
                    $success_total = 0;
                    foreach($ids as $id){
                        $issued = $model->getOne(array('id'=>$id));
                        if($issued['state'] != 0 || $issued['user_id'] != 0){
                            $this->ajax(205,'很遗憾,有人别您手快.');
                        }
                        if($model->update(array('user_id'=>$current_user['user_id'],'state'=>1),array('id'=>$id))){
                            if( $model_user_daijinquan->insert(
                                array('user_id'=>$current_user['user_id'],'v_id'=>$issued['v_id'],'count'=>1,'create_time'=>date("Y-m-d H:i:s"))
                            )){
                                $success_total = $success_total+1;
                            }
                        }
                    }
                    //TODO
                    if($success_total>0){
                        $this->ajax(200,$current_user['user_name'].',您已经成功领取'.count($success_total).'张代金卷.');
                    }else{
                        $this->ajax(203,'很遗憾,有人别您手快.');
                    }
                }else{
                    $this->ajax(202,'代金卷无效.');
                }
            }
        }
    }

    /**
     * 维修单状态改变
     */
    public function repairOrderStateAction(){
        $state = $this->jsonObj->handled;

        $data = $this->model->getOne("id=".$this->jsonObj->id);

        //订单操作权限合法性验证
        switch($state){
            case 1://接单：单子状态必须是未接单状态，且receiver_id是本人
            case 2://报价：单子状态必须是已接单待报价状态，且receiver_id是本人
            case 3://退单：单子状态必须是未接单状态，且receiver_id是本人
            case 5://维修完成待验收：单子状态必须是已支付状态，且receiver_id是本人
                $receiverId = $data['receiver_id'];
                if($receiverId != $this->jsonObj->user_id){

                    $this->ajax(201,'该订单不存在');
                }

                if($data['user_id'] == $this->jsonObj->user_id){

                    $this->ajax(201,'您不能操作自己发起的维修单');
                }
                break;
            case 4://支付：单子状态必须是待支付状态，且user_id是本人
            case 6://评价：单子状态必须是待评价状态，且user_id是本人
            case 7://完成验收：单子状态必须是待验收状态，且user_id是本人
                $userId = $data['user_id'];
                if($userId != $this->jsonObj->user_id){

                    $this->ajax(201,'该订单不存在');
                }
                break;
            default:
                $this->ajax(203,'操作失败');
                break;
        }

        //订单状态合法性
        switch($state){
            case 1://接单：单子状态必须是待接单状态，且receiver_id是本人
                if($data['handled'] != 0){

                    $this->ajax(203,'操作失败');
                }
                break;
            case 2://报价：单子状态必须是已接单待报价状态，且receiver_id是本人
            {
                if($data['handled'] != 1){

                    $this->ajax(203,'操作失败');
                }

                if(!is_numeric($this->jsonObj->price) || $this->jsonObj->price <= 0.0){

                    $this->ajax(202,'输入正确的价格');
                }

                //报价
                $data['price'] = $this->jsonObj->price;
                $data['price_detail'] = $this->jsonObj->price_detail;

                //TODO 产生支付订单
                $orderid = $this->_getorderNo();
                $model_order_list = Controller::createMode($this->default_db,$this->getTableName('order_product_list'));
                //订单详情
                $product = array(
                    'orderid'=>$orderid,
                    'm_id'=>$data['id'],//维修单编号
                    'price'=>$data['price'],
                    'total'=>1,
                    'user_id'=>$data['user_id'],//维修单发起者
                    's_id'=>$data['receiver_id'],//服务提供商
                    'remark'=>$this->jsonObj->price_detail,
                    'time'=>time(),
                );
                //插入操作
                $model_order_list->insert($product);

                //查询用户信息
                $modelUser = Controller::createMode($this->default_db,'t_26_yonghuliebiao');
                $user = $modelUser ->getOne(array('user_id'=>$data['user_id']));
                $deliver_time = $data['scheduled_time'] ? $data['scheduled_time'] : date("Y-m-d H:i:s");
                $params = array(
                    'user_id'=>$data['user_id'],
                    'orderid'=>$orderid,
                    'type'=>1,
                    'total'=>1,
                    'price'=>$data['price'],
                    'truename'=>$data['contact'],
                    'tel'=>$data['mobile']?$data['mobile']:$user['mobile'],
                    'address'=>$data['address'],
                    'deliver_time'=>$deliver_time,
                    'deliver_time_end'=>$deliver_time,
                    'remark'=>$this->jsonObj->price_detail,
                    'buytime'=>time(),
                    'insert_dt'=>date("Y-m-d H:i:s")
                );

                //TODO 待支付记录
                $recode = array(
                    'orderid'=>$orderid,
                    'amount'=>$data['price'],
                    'state'=>0,
                );
                //支付记录
                $modelPayRecode = Controller::createMode($this->default_db,$this->getTableName('zhifujilubiao'));
                $modelPayRecode->insert($recode);

                $modelArray = array();
                array_push($modelArray, $modelUser);
                array_push($modelArray, $modelPayRecode);

                //日志录入
                $logModel = Controller::createMode($this->default_db,'t_29_log_operation');
                array_push($modelArray, $logModel);
                $log = array(
                    'create_time'=>date("Y-m-d H:i:s"),
                    'user_id'=>$this->jsonObj->user_id,
                    'level'=>1,
                    'events'=>"维修报价订单号：".$orderid."参数：".json_encode($this->jsonObj),
                    'state'=>0,
                );

                //支付订单模型
                $orderCreateModel = Controller::createMode($this->default_db,$this->getTableName('order_info'));
                array_push($modelArray, $orderCreateModel);
                if($orderCreateModel->insert($params)){

                    $order = $orderCreateModel->getOne("orderid = '".$orderid."' and user_id=".$data['user_id']);
                    if($order && $order['orderid'] == $orderid){//复审该订单是否插入成功
                        $data['orderid'] = $orderid;//赋值订单号

                        $log['state'] = 1;
                    } else {

                        $log['state'] = 0;
                        $logModel->insert($log);

                        $this->__freeModel($modelArray);
                        unset($product);
                        unset($params);
                        unset($recode);
                        unset($log);

                        $this->ajax(203,'报价失败');
                    }
                }else{

                    $log['state'] = 0;
                    $logModel->insert($log);

                    $this->__freeModel($modelArray);
                    unset($product);
                    unset($params);
                    unset($recode);
                    unset($log);

                    $this->ajax(203,'报价失败');
                }

                $logModel->insert($log);

                unset($product);
                unset($params);
                unset($recode);
                unset($log);
            }
                break;
            case 3://退单：单子状态必须是未接单状态，且receiver_id是本人
                if($data['handled'] != 0){

                    $this->ajax(203,'操作失败');
                }
                if(strlen($this->jsonObj->refuse_remark) < 1){//必须输入退单理由

                    $this->ajax(202,'请输入原因');
                }
                $data['refuse_remark'] = $this->jsonObj->refuse_remark;
                break;
            case 4://支付：单子状态必须是待支付状态，且user_id是本人
                $this->ajax(203,'操作失败');//走订单支付流程改该状态
                break;
            case 5://维修完成待验收：单子状态必须是已支付状态，且receiver_id是本人
                if($data['handled'] != 4){

                    $this->ajax(203,'操作失败');
                }
                break;
            case 6://评价：单子状态必须是待评价状态，且user_id是本人
                if($data['handled'] != 7){

                    $this->ajax(203,'操作失败');
                }
                $this->ajax(203,'操作失败');//TODO 评价流程暂时走订单评价流程
                break;
            case 7://完成验收：单子状态必须是待验收状态，且user_id是本人
                if($data['handled'] != 5){

                    $this->ajax(203,'操作失败');
                }
                break;
            default:
                $this->ajax(203,'操作失败');
                break;
        }

        //赋值新状态
        $data['handled'] = $state;

        if( $this->model->updateData($data,array('id'=>$this->jsonObj->id)) ){

            //支付订单模型
            $orderUpdateModel = Controller::createMode($this->default_db,$this->getTableName('order_info'));
            array_push($modelArray, $orderUpdateModel);
            switch($state){
                case 5://维修完成待验收：订单状态变更为“待收货”状态
                    $orderMap['orderid'] = $data['orderid'];
                    $orderMap['user_id'] = $data['user_id'];

                    $orderUpdateData['handled'] = 1;
                    $orderUpdateModel->update($orderUpdateData, $orderMap);

                    unset($orderUpdateData);
                    unset($orderMap);
                    break;
                case 6://评价

                    $this->ajax(203,'操作失败');//TODO 评价流程暂时走订单评价流程
                    break;
                case 7://完成验收：订单状态变更为“待评价”状态
                    $orderMap['orderid'] = $data['orderid'];
                    $orderMap['user_id'] = $data['user_id'];

                    $orderUpdateData['handled'] = 2;
                    $orderUpdateModel->update($orderUpdateData, $orderMap);

                    unset($orderUpdateData);
                    unset($orderMap);
                    break;
            }

            //推送消息
            $xiaoxi_model = Controller::createMode($this->default_db, 't_29_server_xiaoxi');
            array_push($modelArray, $xiaoxi_model);
            //维修单：msg_type = 4
            $xiaoxiData = array();
            $xiaoxiData['from_id'] = '10000';
            $xiaoxiData['create_time'] = date("Y-m-d H:i:s");
            switch($state){
                case 1://接单
                    $xiaoxiData['msg_content'] = '维修单号'.$this->jsonObj->id.'已被接单';
                    $xiaoxiData['to_id'] = $data['user_id'];
                    break;
                case 2://报价
                    $xiaoxiData['msg_content'] = '维修单号'.$this->jsonObj->id.'已报价，请尽快确认并支付。';
                    $xiaoxiData['to_id'] = $data['user_id'];
                    break;
                case 3://退单
                    $xiaoxiData['msg_content'] = '维修单号'.$this->jsonObj->id.'已被拒绝';
                    $xiaoxiData['to_id'] = $data['user_id'];
                    break;
                case 5://维修完成待验收
                    $xiaoxiData['msg_content'] = '维修单号'.$this->jsonObj->id.'已维修完成，请尽快确认验收';
                    $xiaoxiData['to_id'] = $data['user_id'];
                    break;
                case 7://完成验收
                    $xiaoxiData['msg_content'] = '维修单号'.$this->jsonObj->id.'已完成验收';
                    $xiaoxiData['to_id'] = $data['receiver_id'];
                    break;
                default:
                    $this->ajax(203,'操作失败');
                    break;
            }

            $xiaoxiData['type'] = 1;
            $xiaoxi_model->insert($xiaoxiData);

            $xiaoxiData['title'] = '维修单号'.$this->jsonObj->id.'有最新动态';
            $xiaoxiData['msg_type'] = 4;
            $xiaoxiData['orderid'] = $this->jsonObj->id;
            $this->_pushMessage(1, $xiaoxiData['to_id'], $xiaoxiData, 0);
            unset($xiaoxiData);

            $this->__freeModel($modelArray);
            $this->ajax(200, '操作成功', $data);
        }else{

            $this->__freeModel($modelArray);
            $this->ajax(201, '操作失败', $data);
        }
    }

    /***
     * 认证接口
     */
    public function authentedAction(){
        $map = self::$_extensionArray['keys'];
        foreach($map as $key=>$row ){
            $map[$key] = $this->jsonObj->$key;
        }
        if($_POST || $_GET){
            $params = (array)$this->jsonObj;
            $count = $this->model->count($this->model->getTableName(),"1",$map);
            $data  = $this->model->getOne($map);
            if($this->model->getTableName() == "t_29_ziliaorenzhengbiao"){
                if($data['state'] == 1){
                    $this->ajax(201,"authened",$map);
                }
            }
            if($count == 0){
                if( $this->model->addData($params) ){
                    //附件处理
                    if($this->jsonObj->attachs && count($this->jsonObj->attachs) > 0){

                        $attachModel = Controller::createMode($this->default_db, $this->jsonObj->m.'_attach');//附件模型
                        if($attachModel){

                            foreach($this->jsonObj->attachs as $row){//遍历插入附件数据

                                $dataInfo = (array)$row;
                                $dataInfo['user_id'] = $this->jsonObj->user_id;
                                $attachModel->insert($dataInfo);
                            }
                            $attachModel->close();
                        }

                    }

                    $this->ajax(200,null,$map);
                }else{
                    $this->ajax(417,null,$map);
                }
            }else {
                if( $this->model->updateData($params,$map) ){
                    $this->ajax(200,null,$map);
                }else{
                    $this->ajax(417,null,$map);
                }
            }
        }  else {
            $this->ajax(417,null,$map);
        }
    }

    /**
     * 服务咨询消息查询
     */
    public function selectServerXiaoxiAction(){
        $page_size = $this->jsonObj->page_size?$this->jsonObj->page_size: 10;
        $isGroup = $this->jsonObj->is_group;

        if($this->jsonObj->fields){
            $excs = explode(',',$this->jsonObj->fields);
            foreach(self::$_extensionArray['table_info'] as $key=>$field){
                if(!in_array($key,$excs) ){
                    unset(self::$_extensionArray['table_info'][$key]);
                }
            }
        }elseif($this->jsonObj->except){
            $excs = explode(',',$this->jsonObj->except);
            foreach(self::$_extensionArray['table_info'] as $key=>$field){
                if(in_array($key,$excs) ){
                    unset(self::$_extensionArray['table_info'][$key]);
                }
            }
        } else {
            //TODO 所有字段都展示
        }

        $fileds = implode(',',array_keys(self::$_extensionArray['table_info']));
        $where = $this->parseWhere();
        $order = $this->parseOrder();

        if($isGroup > 0){//分组

            $queryCondition = "SELECT * from ".$this->jsonObj->m." sx where not exists(select from_id from ".$this->jsonObj->m." where sx.from_id=from_id and sx.create_time<create_time) ";

            if(count($order)>0){

                $queryCondition .= " ORDER BY ".implode(",", $order);
            }

            $field_renames = '';
            foreach(self::$_extensionArray['table_info'] as $key=>$field){

                $field_renames .= 'sxb.'.$key.' as '.$key.',';
            }
            $field_renames = substr($field_renames, 0 , (strlen($field_renames) - 1));

            $queryCondition = "SELECT ".$field_renames." from(".$queryCondition.") sxb WHERE from_id = ".$this->jsonObj->user_id." or to_id = ".$this->jsonObj->user_id." LIMIT ".($page_size+1);
            $list = $this->model->execute($queryCondition);
        } else {

            $where .= " and ((from_id = ".$this->jsonObj->from_id." and to_id = ".$this->jsonObj->to_id.") or (from_id = ".$this->jsonObj->to_id." and to_id = ".$this->jsonObj->from_id."))";
            if(count($order)>0){
                $list = $this->model->where($where)->field($fileds)->limit($page_size+1)->order($order)->select();
            }else {
                $list = $this->model->where($where)->field($fileds)->limit($page_size+1)->select();
            }
        }

        if(count($list) == $page_size+1){
            self::$_extensionArray['o']['finish'] = 1;
            self::$_extensionArray['o']['list'] = array_slice($list,0,$page_size);
        } else {
            self::$_extensionArray['o']['finish'] = 0;
            self::$_extensionArray['o']['list'] = is_array($list)?$list:array();
        }
        self::$_extensionArray['o']['list'] = is_array(self::$_extensionArray['o']['list'])?self::$_extensionArray['o']['list']:array();

        if($isGroup > 0){//分组

            $userModel = Controller::createMode($this->default_db, $this->getTableName('yonghuliebiao'));//用户模型
            $userSelf = $userModel->getOne("user_id=".$this->jsonObj->user_id);
            foreach(self::$_extensionArray['o']['list'] as $key=>$value){

                if($value['from_id'] == $this->jsonObj->user_id){

                    self::$_extensionArray['o']['list'][$key]['from_name'] = $userSelf['user_name'];
                } else {

                    $user = $userModel->getOne("user_id=".$value['from_id']);
                    self::$_extensionArray['o']['list'][$key]['from_name'] = $user['user_name'];
                }

                if($value['to_id'] == $this->jsonObj->user_id){

                    self::$_extensionArray['o']['list'][$key]['to_name'] = $userSelf['user_name'];
                } else {

                    $user = $userModel->getOne("user_id=".$value['to_id']);
                    self::$_extensionArray['o']['list'][$key]['to_name'] = $user['user_name'];
                }
            }

            $userModel->close();
        }

        $this->ajax(200,null,self::$_extensionArray['o']);
    }

    /**
     * @param $msg_type
     * @param $user_id
     * @param $params
     * @param int $notify_type:0.透传 1/2非透传
     * @return mixed
     */
    private function _pushMessage($msg_type,$user_id,$params,$notify_type = 0){
        $model = $this->module('igetui');
        switch($this->jsonObj->api_key){
            case 'guipiao.grain':
            case 'guipiao':
            $model->setIGetuiConfig('kudRIP8z606x8prvdFwS93','OZQwcbIWKr7ztD2tUlZdr2','hlv55QghDP9EHGuxLCCBY8');
                break;
            case 'jiku999.grain':
                $serviceProviderModel = Controller::createMode($this->default_db, 't_29_service_provider');
                if(is_object($serviceProviderModel)) {

                    $provider = $serviceProviderModel->getOne(array('user_id'=>$user_id));
                    if($provider['user_id']){

                        $model->setIGetuiConfig('7Y7jpXrdC89YRBqxHFkRV7','5tzz1BU4C67b2Swg9v7ee2','Sl6klF2gwy61Dl6qwccxlA');
                    } else {

                        $model->setIGetuiConfig('Avp63Lbelj5oKgeo7RYjBA','LTq9eAd1M16WH4n6DZpY6A','xFQctFdNsy5JyzEmwhOXAA');
                    }

                    $serviceProviderModel->close();
                } else {

                    $model->setIGetuiConfig('Avp63Lbelj5oKgeo7RYjBA','LTq9eAd1M16WH4n6DZpY6A','xFQctFdNsy5JyzEmwhOXAA');
                }

                break;
            case 'junli.grain':
                $model->setIGetuiConfig('ZGdAaZORBVAjWGbau9f5m8','p6k2SLlCsLAn01VXOeDps6','wxDy2B6c6886Cy3NddvFS5');
                break;
            case 'grain':
                $model->setIGetuiConfig('kudRIP8z606x8prvdFwS93','OZQwcbIWKr7ztD2tUlZdr2','hlv55QghDP9EHGuxLCCBY8');
                break;
            default:
        }

        $client_id = $this->_getClientIdByUserId($user_id);
        switch($msg_type){
            //回复
            case 1:
                $res = $model->push($client_id,$params,$notify_type);
                break;
            //提问
            case 2:
                $res = $model->push($client_id,$params,$notify_type);
                break;
            case 3:
                $res = $model->push($client_id,$params,$notify_type);
                break;
        }
        return $res;
    }

    private function _getClientIdByUserId($user_id){
        $model = Controller::createMode($this->default_db,$this->getTableName('yonghupeizhi'));
        $result = $model->find($user_id,'getui_client_id');
        return $result['getui_client_id'];
    }

    public function funcAction(){
        if(is_array($this->jsonObj->func)){
            foreach($this->jsonObj->func as $key=>$val ){
                if($this->jsonObj->func[$key][2] == 'increment'){
                    if(isset($this->jsonObj->func[$key][3]) && isset($this->jsonObj->func[$key][4])){
                        $map[$this->jsonObj->func[$key][3]] = $this->jsonObj->func[$key][4];
                        $data = array();
                        $data[$this->jsonObj->func[$key][1]] = "{$this->jsonObj->func[$key][1]}+1";
                        Controller::createMode($this->default_db,$this->jsonObj->func[$key][0])->update($data,$map);
                    }
                }
            }
        }
        $this->ajax(200);
    }

    private function _containMap($field = ''){
        foreach($this->jsonObj->map as $row){
            if($row[0] == $field) return true;
        }
       return false;
    }

    private function _callback(){
        if($this->returnJsonObj->code !== 200){
            return;
        }
        if(is_array($this->jsonObj->callback)){
            if($this->jsonObj->callback[0][2] == 'add'){
                if(isset($this->jsonObj->callback[1][3]) && isset($this->jsonObj->callback[1][4])){
                    $map1[$this->jsonObj->callback[1][3]] = $this->jsonObj->callback[1][4];
                }else if(isset($this->jsonObj->callback[0][3]) && isset($this->jsonObj->callback[0][4])){
                    $map1[$this->jsonObj->callback[0][3]] = $this->jsonObj->callback[0][4];
                }else{
                    if(strstr($this->jsonObj->m,"zhutizanliebiao")){
                        $map2['id'] = $this->jsonObj->t_id?$this->jsonObj->t_id:$this->jsonObj->id;
                    }else if(strstr($this->jsonObj->m,"t_51_pinglunzanliebiao")){
                        $map2['c_id'] = $this->jsonObj->t_id?$this->jsonObj->t_id:$this->jsonObj->id;
                    }else{
                        $map2['thread_id'] = $this->jsonObj->root_thread_id?$this->jsonObj->root_thread_id:$this->jsonObj->thread_id;
                    }
                }
                $data = array();
                $data[$this->jsonObj->callback[0][1]] = "{$this->jsonObj->callback[0][1]}+1";
                if($map2){
                    Controller::createMode($this->default_db,$this->jsonObj->callback[0][0])->update($data,$map2);
                }
                if($map1){
                    Controller::createMode($this->default_db,$this->jsonObj->callback[0][0])->update($data,$map1);
                }
            }
        }
    }

    /**
     * @param $menuInfo
     * @param $user_id
     */
    private function __canUseVirtualCoin($menuInfo, $user_id, $closeModel = false)
    {

            //建立模型
            $virtualCoin_model = Controller::createMode($this->default_db, 't_29_jikubibiandongmingxibiao');

            $supplierIdArray = array();
            foreach ($menuInfo as $menu) {

                if ($menu->m_supplier > 0)
                    array_push($supplierIdArray, $menu->m_supplier);
            }
            $limit_supplier_id = implode(',', $supplierIdArray);
            unset($supplierIdArray);

            //专用机库币查询条件
            $specil_coin_where = "user_id=".$user_id." and limit_supplier_id in (".$limit_supplier_id.")";
            //专用机库币查询
            $specialSumVirtualCoinGroupBySupplier = $virtualCoin_model->from('t_29_jikubibiandongmingxibiao', array('coinnum' => 'SUM(amount)', 'supplier' => 'limit_supplier_id'))->where($specil_coin_where)->group("supplier")->select();

            //统计订单可以用的专用机库币数量
            $total = 0;
            foreach ($specialSumVirtualCoinGroupBySupplier as $key => $coin) {

                foreach ($menuInfo as $menu) {

                    if ($menu->m_supplier == $coin['supplier']) {

                        $priceToCoin = ceil($menu->price * $menu->total * 100);//进一取整
                        if ($priceToCoin >= $coin['coinnum']) {//机库币：人民币=100:1

                            $total += $coin['coinnum'];//统计
                            $specialSumVirtualCoinGroupBySupplier[$key]['coinnum'] = 0;//置0
                        } else {

                            $total += $priceToCoin;//统计
                            $specialSumVirtualCoinGroupBySupplier[$key]['coinnum'] -= $priceToCoin;//减去$priceToCoin
                        }
                    }
                }
            }
            unset($menu);
            unset($specialSumVirtualCoinGroupBySupplier);

            //普通机库币查询
            $normalVirtualCoin_sum = $virtualCoin_model->getOne("user_id=".$user_id." and limit_supplier_id=0", null, array('coinnum' => 'SUM(amount)'));
            $total += $normalVirtualCoin_sum['coinnum'];

            //释放模型
            if ($virtualCoin_model && $closeModel) {

                $virtualCoin_model->close();
            }
        return ($total <= 0 ? 0 : $total);
    }

    /**
     * 机库币使用
     * @param $menuInfo 使用商品
     * @param $user_id 使用人
     * @param $orderid 使用订单号
     * @param int $virtualCoinNum 使用数量
     */
    private function __useVirtualCoin($menuInfo, $user_id, $orderid, $virtualCoinNum = 0)
    {
        if($virtualCoinNum > 0 && $user_id > 0){

            //建立模型
            $virtualCoin_model = Controller::createMode($this->default_db, 't_29_jikubibiandongmingxibiao');

            $supplierIdArray = array();
            foreach ($menuInfo as $menu) {

                if ($menu->m_supplier > 0)
                    array_push($supplierIdArray, $menu->m_supplier);
            }
            $limit_supplier_id = implode(',', $supplierIdArray);
            unset($supplierIdArray);

            //专用机库币查询条件
            $specil_coin_where = "user_id=" . $user_id . " and limit_supplier_id in (" . $limit_supplier_id . ")";
            //专用机库币查询
            $specialSumVirtualCoinGroupBySupplier = $virtualCoin_model->from('t_29_jikubibiandongmingxibiao', array('coinnum' => 'SUM(amount)', 'supplier' => 'limit_supplier_id'))->where($specil_coin_where)->group("supplier")->select();

            /***抵扣专用币 start***/
            //抵扣参数type|0=普通|1=专用，limit_supplier_id定向供应商编号
            $params = array(
                'user_id'=>$user_id,
                'orderid'=>$orderid,
                'amount'=>0,
                'remark'=>'消费',
                'type'=>0,
                'limit_supplier_id'=>0,
                'create_time'=>date("Y-m-d H:i:s")
            );
            //待抵扣总数
            $total = $virtualCoinNum;
            foreach ($specialSumVirtualCoinGroupBySupplier as $key => $coin) {

                foreach ($menuInfo as $menu) {

                    if ($menu->m_supplier == $coin['supplier'] && $total > 0) {

                        $priceToCoin = ceil($menu->price * $menu->total * 100);//进一取整
                        if ($priceToCoin >= $coin['coinnum']) {//机库币：人民币=100:1
                            $params['amount'] = -$coin['coinnum'];//数量
                            $params['type'] = 1;//专用
                            $params['limit_supplier_id'] = $coin['supplier'];//专用供应商编号
                            $virtualCoin_model->insert($params);//生成使用记录

                            $total -= $coin['coinnum'];//统计
                            $specialSumVirtualCoinGroupBySupplier[$key]['coinnum'] = 0;//置0
                        } else {
                            $params['amount'] = -$priceToCoin;//数量
                            $params['type'] = 1;//专用
                            $params['limit_supplier_id'] = $coin['supplier'];//专用供应商编号
                            $virtualCoin_model->insert($params);//生成使用记录

                            $total -= $priceToCoin;//统计
                            $specialSumVirtualCoinGroupBySupplier[$key]['coinnum'] -= $priceToCoin;//减去$priceToCoin
                        }
                    }
                }
            }
            unset($menu);
            unset($specialSumVirtualCoinGroupBySupplier);
            /***抵扣专用币 end***/

            //普通机库币查询
            $normalVirtualCoin_sum = $virtualCoin_model->getOne("user_id=" . $user_id . " and limit_supplier_id=0", null, array('coinnum' => 'SUM(amount)'));
            if($total > 0 && $normalVirtualCoin_sum['coinnum'] >= $total){//抵扣普通币

                $params['amount'] = -$total;//数量
                $params['type'] = 0;//普通
                $params['limit_supplier_id'] = 0;//普通

                $virtualCoin_model->insert($params);
            }


            //释放模型
            if ($virtualCoin_model) {

                $virtualCoin_model->close();
            }
        }
    }
}
